java文件读写

java文件读写

软件构造lab1中遇到了文件读写的问题,自己用的一种简单的相对寻址的方法,但是健壮性不足,只要文件改变位置,就会报错。在和同学讨论的时候发现了更好的方法,故记录在这里,方便查看

用软件构造的lab1目录结构举例:
Lab1-XXX
|– src
|—|– P1
|—|—|-> MagicSquare.java
|—|—|– txt
|—|—|—|-> 1.txt
|—|—|—|-> 2.txt
|—|—|—|-> …
|—|—|—|-> 5.txt

eclipse的相对路径是相对.project而言的!!!

一般路径最好写成 / /等价于\\

例:D:/test/main.java

基本方法

//Java7的try-with-resources可以优雅关闭文件,异常时自动关闭文件;详细解读https://stackoverflow.com/a/12665271

  • 读取文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    String pathname = "src/P1/txt/1.txt";
    public boolean isLegalMagicSquare() {
    try(BufferedReader input=new BufferedReader(
    new FileReader(pathname))) {
    String line;
    while ((line = input.readLine()) != null) {
    // 一次读入一行数据
    System.out.println(line);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
  • 写入文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    //方法1
    String pathname = "src/P1/txt/1.txt";
    public static void writeFile() {
    try {
    File writeName = new File(pathname);
    writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
    try (PrintWriter out=new PrintWriter(
    new FileWriter(writeName))
    ) {
    out.println("方法1"); // \r\n即为换行
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    //方法2
    BufferedWriter out=new BufferedWriter(
    new FileWriter(writeName))
    out.write("方法1\r\n"); // \r\n即为换行
    out.write("hhhh\r\n"); // \r\n即为换行
    out.flush(); // 把缓存区内容压入文件

下面有三个进阶一丢丢的方法,也许可以帮助改进你的代码

改进1

使用System.getProperty("key")

key .
user.name 用户的账户名称
user.home 用户的主目录
user.dir 用户的当前工作目录
1
2
3
4
5
String path1=System.getProperty("user.dir");
System.out.println(path1);

输出:
D:\JavaWorkPlace\test

改进2

查询某类的.class文件所在目录

1
2
3
4
5
6
7
8
9
10
11
String path1=MagicSquare.class.getResource("").getPath();
String path2=MagicSquare.class.getResource("/").getPath();
String path3=MagicSquare.class.getResource("/P1/txt").getPath();
System.out.println(path1);
System.out.println(path2);
System.out.println(path3);

输出:
/D:/JavaWorkPlace/test/bin/P1/
/D:/JavaWorkPlace/test/bin/
/D:/JavaWorkPlace/test/bin/P1/txt //前提这个文件夹得存在

改进3

查询某类的classloader所在目录

1
2
3
4
5
String path1=MagicSquare.class.getClassLoader().getResource("").getPath();
System.out.println(path1);

输出:
/D:/JavaWorkPlace/test/bin/
#
You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×