标签:test style system otf http bsp writer except iter
FileReader和FileWriter的案例
package com.model.io.reader.filereader; import org.junit.Test; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/6/18 15:29 */ public class FileReaderDemo01 { @Test public void reader() throws IOException { String filePath="D:\\qq\\IDEA\\IdeaProjects\\java_mianshi_test\\mianshi_io\\src\\main\\resources\\Reader\\CopyDemo01.txt"; int readCount=0; FileReader fileReader=null; try { fileReader=new FileReader(filePath); while((readCount=fileReader.read())!=-1){ System.out.print((char) readCount); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally { if (fileReader!=null) { fileReader.close(); } } } @Test public void reader02() throws IOException { String filePath="D:\\qq\\IDEA\\IdeaProjects\\java_mianshi_test\\mianshi_io\\src\\main\\resources\\Reader\\CopyDemo01.txt"; char[] buff = new char[8]; int readCount=0; FileReader fileReader=null; try { fileReader=new FileReader(filePath); while((readCount=fileReader.read(buff))!=-1){ System.out.print(new String(buff,0,readCount)); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally { if (fileReader!=null){ fileReader.close(); } } } }
FileWriter的注意点;创建对象是,要指定是覆盖还是追加的方式;还要注意将最后将输出数据的对象关闭,或者进行flash,否则数据还是在内存中,没有真正的写入到文件中。
package com.model.io.writer.filewriter; import org.junit.Test; import java.io.FileWriter; import java.io.IOException; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/6/18 15:30 */ public class FileWriterDemo01 { @Test public void writer() throws IOException { String filePath="D:\\qq\\IDEA\\IdeaProjects\\java_mianshi_test\\mianshi_io\\src\\main\\resources\\Writer\\a.txt"; FileWriter fileWriter=null; try { /** * 注意点:是追加的方式还是覆盖的方式添加数据 * */ fileWriter=new FileWriter(filePath,true); //1.写入单个字符 fileWriter.write(‘z‘); //2.写入指定的数组 String str="hello,word"; fileWriter.write(str.toCharArray()); //3.写入指定字符数组的一部分 fileWriter.write(str.toCharArray(), 0, str.length()); //4.写入字符串 fileWriter.write(str); //5.写入字符串的一部分 fileWriter.write(str, 0, str.length()); } catch (IOException e) { e.printStackTrace(); } finally { /** * 注意点:写完之后要关闭资源,否则内容无法写入到文件中 * */ if (fileWriter != null) { // fileWriter.flush(); fileWriter.close(); } } } }
java--IO--FileReader和FileWriter
标签:test style system otf http bsp writer except iter
原文地址:https://www.cnblogs.com/zzhAylm/p/14899706.html