本文共 3385 字,大约阅读时间需要 11 分钟。
InputStream和Reader都是抽象类,本身不能创建实例,他们分别有一个读取文件的输入流:FileInputStream和FileReader,它们都是节点流(会直接和指定文件关联)。
package filetest;import java.io.FileInputStream;import java.io.FileNotFoundException;public class FileInputStreamTest { public static void main(String[] args) { try { //创建字节输入流 FileInputStream fis=new FileInputStream("first.txt"); //穿件一个长度为1024的字节数组 byte[] bbuf=new byte[1024]; //保存实际读取的字节数 int hasRead=0; //使用循环来重复取字节 while((hasRead=fis.read(bbuf))>0) { //将读取出来的字节数组转换成字符串输出 System.out.println(new String(bbuf,0,hasRead)); } fis.close(); //关闭文件输入流 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
package filetest;import java.io.FileReader;import java.io.IOException;public class FileReadderTest { public static void main(String[] args) throws IOException { //创建字符输入流 FileReader fr=new FileReader("E:\\Java-IO\\first.txt"); //创建字符数组 char[] cbuf =new char[512]; //保存读取字符数 int hasRead=0; //使用循环来读取字符 while((hasRead=fr.read(cbuf))>0) { //将字符数组转换成字符串输出 System.out.println(new String(cbuf,0,hasRead)); } fr.close(); }}
package filetest;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;public class FileOutputStreamTest { public static void main(String[] args) { try { //创建字节输入流 FileInputStream fis=new FileInputStream("E:\\Java-IO\\first.txt"); //创建字节输出流 FileOutputStream fos=new FileOutputStream("E:\\Java-IO\\second.txt"); byte[] bbuf=new byte[32]; int hasRead=0; //循环从输入流中取出数据 while((hasRead=fis.read(bbuf))>0) { //每读取一次,就写入文件输出流 fos.write(bbuf,0,hasRead); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
package filetest;import java.io.FileWriter;import java.io.IOException;public class FileWriterTest { public static void main(String[] args) { try { FileWriter fw=new FileWriter("E:\\Java-IO\\poem.txt"); //Windows平台的换行符是"\r\n",linux平台使用"\n" fw.write("张三\r\n"); fw.write("李四\r\n"); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
转载地址:http://eykni.baihongyu.com/