软件构造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
13String 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 | 用户的当前工作目录 | ||
|
改进2
查询某类的.class文件所在目录
1 | String path1=MagicSquare.class.getResource("").getPath(); |
改进3
查询某类的classloader所在目录
1 | String path1=MagicSquare.class.getClassLoader().getResource("").getPath(); |