文件写入
BufferedWriter out = new BufferedWriter(new FileWriter("nowcoder.txt")); out.write("牛客教程"); out.close();
文件读取
BufferedReader in = new BufferedReader(new FileReader("test.log")); String str; while ((str = in.readLine()) != null) { System.out.println(str); }
创建临时文件
File temp = File.createTempFile("test", ".txt"); System.out.println("文件路径: "+temp.getAbsolutePath()); temp.deleteOnExit();//程序退出文件删除 BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write("aString"); System.out.println("临时文件已创建:"); out.close();
修改最后修改时间
Date filetime = new Date(fileToChange.lastModified()); System.out.println(filetime.toString()); System.out.println(fileToChange.setLastModified(System.currentTimeMillis()));
获取文件大小
file.length()
重命名
File oldName = new File("C:/program.txt"); File newName = new File("C:/java.txt"); if(oldName.renameTo(newName)) { System.out.println("已重命名"); } else { System.out.println("Error"); }
设置文件只读
file.setReadOnly() 和 file.canWrite() 方法
检测文件是否存在
file.exists()
设置只读
System.out.println(file.setReadOnly());
System.out.println(file.canWrite());
在指定目录中创建文件
File dir = new File("C:/"); file = File.createTempFile ("JavaTemp", ".javatemp", dir);