1.Java File api 文档
(1) java.io.File
https://docs.oracle.com/javase/8/docs/api/java/io/File.html
(2) java.nio.file
https://docs.oracle.com/javase/8/docs/api/java/nio/file/package-summary.html
为File 补充了许多API , 例如读写操作等
Paths / Files/ FileSystems 等文件
2.构造方法
public File(String pathname)
Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
public File(String parent,String child)
Creates a new File instance from a parent pathname string and a child pathname string.
public File(File parent, String child)
Creates a new File instance from a parent abstract pathname and a child pathname string.
public File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract pathname.
3.创建File 对象
(1) 仅根据文件名创建File 对象
final String fileName = "input.txt";
File file = new File(fileName);
if (!file.exists()) { //第一次为false, 因此需要创建真实的文件
file.createNewFile();
}
System.out.println("getName="+file.getName()); // input.txt
System.out.println("getPath="+file.getPath()); // input.txt
System.out.println("getAbsolutePath="+file.getAbsolutePath()); // E:\Workspace\AndroidStudio\JavaTest\input.txt
System.out.println("getCanonicalPath="+file.getCanonicalPath()); // E:\Workspace\AndroidStudio\JavaTest\input.txt
即在工程JavaTest的根目录下 (而不是预期的src 代码的目录下)
这个和 System.getProperty("user.dir") 的路径是一样的, 项目的绝对路径。
获取当前项目路径参考: https://stackoverflow.com/questions/4871051/how-to-get-the-current-working-directory-in-java
java.io package resolve relative pathnames using current user directory. The current directory is represented as system property,
that is, user.dir and is the directory from where the JVM was invoked.
(2) 根据文件所在的目录 即 文件名创建(待续)
4. 读写文件
(1) 读取文件内容
一行一行读取: Files.readAllLines, 返回结果为list列表即 List<String>
private static List<String> readLineFromFile(String pathName) throws IOException {
System.out.println("---readLineFromFile pathName=" + pathName);
File file = new File(pathName);
if (!file.exists()) {
System.out.println("readLineFromFile file is not exist and create new ");
file.createNewFile();
return null;
}
List<String> strings = Files.readAllLines(Paths.get(file.getName()), StandardCharsets.UTF_8);//Paths.get(pathName);
return strings;
}
(2)写入文件
把list 内容写入到文件中: Files.write
private static void writeFile(String pathName, List<String> texts) throws IOException {
File file = new File(pathName);
if(!file.exists()){
System.out.println("writeFile file is not exist and create new ");
file.createNewFile();
}
Files.write(Paths.get(file.getName()), texts, StandardCharsets.UTF_8);//Paths.get(pathName);
}
5. 注意
(1). File 实例对象file创建后, 不一定就存在对应的“物理文件” (例如 xx.txt)
此时可以使用 file.exists() 判读“物理文件”是否存在, 如果不存在,则可以用 file.createNewFile() 创建
185

被折叠的 条评论
为什么被折叠?



