package bytetest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamDemo {
public static void main(String[] args) throws IOException{
writeFile();
readFile1();
readFile2();
readFile3();
}
public static void writeFile() throws IOException{
FileOutputStream fos=new FileOutputStream("fos.txt");
//没有缓冲区,不需要刷新
fos.write("abcde阿飞".getBytes());
fos.close();
}
public static void readFile1() throws IOException{ //一次读一个字节
FileInputStream fis=new FileInputStream("fos.txt");
int ch=0;
while((ch=fis.read())!=-1){
System.out.println((char)ch);
}
fis.close();
}
public static void readFile2() throws IOException{ //一次读一个数组
FileInputStream fis=new FileInputStream("fos.txt");
byte[]buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
fis.close();
}
public static void readFile3() throws IOException{ //利用available定义刚刚好大小的数组
FileInputStream fis=new FileInputStream("fos.txt");
byte[]buf=new byte[fis.available()]; //慎用,防止内存溢出
fis.read(buf);
System.out.println(new String(buf));
fis.close();
}
}
文件读写的简单例子(字节流)
最新推荐文章于 2020-02-11 14:27:28 发布