通常情况使用字节流,可以读取文本(文本中出现汉字需要转换成(字符流),或者直接使用字符流),视频,音频等格式
public static void main(String[] args) throws IOException {
FileInputStream fis =new FileInputStream ("w.jpeg");//已知的图片
FileOutputStream fos=new FileOutputStream("ww.jpeg");//最后保存成ww.jpeg
byte [] b= new byte[1024]; //字节流每次读取的是字节,因此新建一个byte 数组
int len =0;
while((len=fis.read(b))!=-1) { //当读到文件末尾的时候,会返回一个-1,没有到末尾时,len 表示读取的字节数
fos.write(b, 0, len);
} fw.close();
}
字符流在读取视频音频的时候,会出现丢失数据的情况(转换错误),因此不再这种情况下使用
字符流读取文本,文字:
public static void main(String[] args) throws IOException {
FileReader fr =new FileReader("a.txt") ; //已知的文本文档
FileWriter fw= new FileWriter("b.txt"); //接收的文档
char [] b= new char[1024]; //读取的是字符
int len =0;
while((len=fr.read(b))!=-1) {
fw.write(b, 0, len);
}
fw.close();//一般都要对流做处理,进行关闭
}
字节转换流:(字节流转字符流)InputStreamReader
public static void main(String[] args) throws IOException {
FileInputStream fis =new FileInputStream ("a.txt");
InputStreamReader isr =new InputStreamReader(fis);
char c [] =new char[100];
isr.read(c);
for (int i = 0; i < c.length; i++) {
System.out.print((char)c[i]);
}
isr.close();
}