import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.LineNumberReader; import java.nio.Buffer; public class io { public static void main(String[] args) throws IOException { writeFile(); readFile1(); readFile2(); } //写入 public static void writeFile() throws IOException { FileOutputStream fos = new FileOutputStream("fos.txt"); fos.write("abcd".getBytes()); fos.close(); } //读出 public static void readFile1() throws IOException { FileInputStream fis1 = new FileInputStream("fos.txt"); int ch=0; while((ch=fis1.read())!=-1) //一个一个读 { System.out.println((char)ch); } fis1.close(); } public static void readFile2() throws IOException { FileInputStream fis2 = new FileInputStream("fos.txt"); byte[] buf = new byte[1024]; //缓冲区 int len = 0; while((len=fis2.read(buf))!=-1) //以数组大小读入 返回值是读入的个数 { System.out.println(new String (buf,0,len)); } fis2.close(); FileInputStream fis3 = new FileInputStream("fos.txt"); //fis2.available 文件中字节的个数 int num = fis3.available(); //定义一个刚刚好的缓冲区,不能用与文件很大的 和爆内存 byte[] buf2 = new byte[fis3.available()]; fis3.read(buf2); System.out.println(num+":"+new String(buf2)); fis3.close(); } }
原文地址:http://www.cnblogs.com/wzz1020/p/3858797.html