使用了try-with-resource语法(JDK1.7及以上),代码更加便捷
Junit测试样例,先写入文件,再读出来:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config-service-test.xml")
public class FileTest {
@Test
public void testFile() {
write();
read();
}
/**
* 读
*/
public void read() {
String path = "D:\\file\\myFile.txt";
//Java7的try-with-resources可以优雅关闭文件,异常时自动关闭文件;详细解读https://stackoverflow.com/a/12665271
try (FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader)
) {
String line;
while ((line = br.readLine()) != null) {
// readLine一行一行读
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 写
*/
public static void write() {
try {
File path = new File("D:\\file\\myFile.txt");
path.createNewFile();
try (FileWriter writer = new FileWriter(path);
BufferedWriter out = new BufferedWriter(writer)
) {
out.write("我写入的内容");
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}