java文件读写


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

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

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

基本方法

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

  • 读取文件
    String pathname = "src/P1/txt/1.txt";
    public boolean isLegalMagicSquare() {
    try(BufferedReader input=new BufferedReader(
                new FileReader(pathname))) {
            String line;    
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 写入文件
    //方法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用户的当前工作目录
String path1=System.getProperty("user.dir");
System.out.println(path1);

输出:
D:\JavaWorkPlace\test
改进2

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

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所在目录

String path1=MagicSquare.class.getClassLoader().getResource("").getPath();
System.out.println(path1);

输出:
/D:/JavaWorkPlace/test/bin/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值