流的定义必须在try catch之外,这样的话可以在finally里调用close()方法关闭资源,若直接在try里面使用
FileInputStream fis = new FileInputStream(filePath)定义的话,则无法关闭资源
public static void main(String[] args) throws IOException {
// 读取文件(读文件时,文件可以为空,但必须存在该文件,否则报错)
FileInputStream fis = null;
String result = "";
String filePath = "D:/self/name.txt";
try {
fis = new FileInputStream(filePath);
int size = fis.available();
byte[] bytes = new byte[size];
fis.read(bytes);
result = new String(bytes);
System.out.println(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fis.close();
}
// 写入文件(文件可以不存在,会自动创建)
filePath = "D:/self/name.txt";
List<String> list = new ArrayList<>();
list.add("gga0");
list.add("gga1");
list.add("gga2");
list.add("gga3");
list.add("gga4");
list.add("gga5");
list.add("gga6");
list.add("gga7");
list.add("gga8");
String content = "";
FileOutputStream fos = null;
for (int i = 0; i < list.size(); i++) {
try {
// true代表叠加写入,没有则代表清空一次写一次
fos = new FileOutputStream(filePath,true);
content = list.get(i);
byte[] bytes = content.getBytes();
fos.write(bytes);
// 换行
fos.write("\r\n".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fos.close();
}
}
}