简单的IO流学习
String filePath="D:\\chromelog\\爱丁堡.txt";
File file = new File(filePath);
if (!file.exists()){
try {
boolean newFile = file.createNewFile();
if (newFile)
System.out.println("文件创建成功");
else
System.out.println("文件创建失败");
} catch (IOException e) {
e.printStackTrace();
}
}
String text="今天是2021/2/25,有雨\r\n" +
"明天是2021/2/26,还有雨\r\n" +
"明天是2021/2/27,还有雨\r\n" +
"明天是2021/2/28,还有雨";
/* FileOutputStream 类的使用:将内容写入文件 */
try(FileOutputStream fileOutputStream = new FileOutputStream(filePath)){//try 语法糖 自动关闭流
//1、根据文件路径创建输出流
//FileOutputStream fileOutputStream = new FileOutputStream(filePath);
//2、把string转换为byte数组;
byte[] bytes = text.getBytes();
//3、把byte数组输出;
fileOutputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
/* FileInputStream类的使用:读取文件内容 */
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
//1. 根据path路径实例化一个输入流的对象
//2. 返回这个输入流中可以被读的剩下的bytes字节的估计值;
int available = fileInputStream.available();
//3. 根据输入流中的字节数创建byte数组;
byte[] bytes = new byte[available];
//4.把数据读取到数组中;
fileInputStream.read(bytes);
//5.根据获取到的Byte数组新建一个字符串,然后输出;
System.out.println(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
String str="字符流写入\r\n字符流读入";
/* 字符流写入 */
try (FileWriter fileWriter = new FileWriter(filePath)) {
fileWriter.write(str);
} catch (IOException e) {
e.printStackTrace();
}
/* 字符流读入 1 */
try (FileReader fileReader = new FileReader(filePath)) {
int read = fileReader.read();
while (read!=-1){
System.out.println((char) read);
read=fileReader.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/* 字符流读入 2 */
try (FileReader fileReader = new FileReader(filePath)) {
char[] chars = new char[1024];
int read = 0;
while ((read=fileReader.read(chars))!=-1){
}
System.out.println(new String(chars));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/* 字符流读入 3 */
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));) {
String strings=null;
while ((strings=bufferedReader.readLine())!=null){
System.out.println(strings);//字符流写入
//字符流读入
}
System.out.println("zongji "+strings);//zongji null
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}