字符节点流(FileReader/FileWriter)
读取文件步骤
- 建立一个流对象,将已存在的一个文件加载进流。
FileReader fr = new FileReader(new File(“Test.txt”)); - 创建一个临时存放数据的数组。
char[] ch = new char[1024]; - 调用流对象的读取方法将流中的数据读入到数组中。
fr.read(ch); - 关闭资源。
fr.close();
写入文件
- 创建流对象,建立数据存放文件
FileWriter fw = new FileWriter(new File(“Test.txt”));
- 调用流对象的写入方法,将数据写入流
fw.write(“hongkang”);
- 关闭流资源,并将流中的数据清空到文件中。
fw.close();
public void testFileReader1() {FileReader fr = null;try {//1.File类的实例化File file = new File("hello.txt");//2.FileReader流的实例化fr = new FileReader(file);//3.读入的操作//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1char[] cbuf = new char[5];int len;while((len = fr.read(cbuf)) != -1){//方式一://错误的写法// for(int i = 0;i < cbuf.length;i++){// System.out.print(cbuf[i]);// }//正确的写法// for(int i = 0;i < len;i++){// System.out.print(cbuf[i]);// }//方式二://错误的写法,对应着方式一的错误的写法// String str = new String(cbuf);// System.out.print(str);//正确的写法String str = new String(cbuf,0,len);System.out.print(str);}} catch (IOException e) {e.printStackTrace();} finally {if(fr != null){//4.资源的关闭try {fr.close();} catch (IOException e) {e.printStackTrace();}}}}
字节节点流(FileInputStream/FileOutputStream)
public void copyFile(String srcPath,String destPath){FileInputStream fis = null;FileOutputStream fos = null;try {//创建文件File srcFile = new File(srcPath);File destFile = new File(destPath);//创建数据流fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);//复制的过程byte[] buffer = new byte[1024];int len;while((len = fis.read(buffer)) != -1){//将fis文件内容读入到数组bufferfos.write(buffer,0,len);//将数组内容写入到fos}} catch (IOException e) {e.printStackTrace();} finally {if(fos != null){//try {fos.close();} catch (IOException e) {e.printStackTrace();}}if(fis != null){try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
使用说明
- 定义文件路径时,注意:可以用“/”或者“\”。
- 在写入一个文件时,如果使用构造器FileOutputStream(file),则目录下有同名文件将被覆盖。
- 如果使用构造器FileWriter(file,true)或FileOutputStream(file,true),则目录下的同名文件不会被覆盖, 在文件内容末尾追加内容。
- 在读取文件时,必须保证该文件已存在,否则报异常。
- File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
- 字节流操作字节,比如:.mp3,.avi,.rmvb,mp4,.jpg,.doc,.ppt
- 字符流操作字符,只能操作普通文本文件。最常见的文本文 件:.txt,.java,.c,.cpp 等语言的源代码。尤其注意.doc,excel,ppt这些不是文本文件。
