FileInputStream、FileOutputStream
- 字节流:顾名思义读取的是字节
- 常用于处理非文本文件
1. FileInputStream
int read()
int read(byte[] b)
int read(byte[] b, int off,int len)
public void test1() throws IOException
{
File file = new File("text.txt");
FileInputStream fis = new FileInputStream(file);
byte[] buf=new byte[5];
int len;
while((len=fis.read(buf))!=-1)
System.out.print(new String(buf,0,len));
fis.close();
}
不难发现"HelloWorld23"、"界"没有乱码,但是"世"乱码了
原因在于我的IDE使用UTF-8编码,在UTF-8中"HelloWorld23"是1字节,所以每次读取1个或多个字节不会乱码,
但是"世界"占用6(2*3=6)字节,所以每次读取5个字节可能会造成乱码
2. FileOutputStream
FileOutputStream(File file)
FileOutputStream(File file, boolean append)
FileOutputStream(String name)
FileOutputStream(String name, boolean append)
void write(int b)
void write(byte[] b)
void write(byte[] b,int off,int len)
File file = new File("text2.txt");
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(97);
fos.write(356);
String str1="abcdefg";
String str2="世界";
byte[] by1=str1.getBytes();
byte[] by2=str2.getBytes();
fos.write(by1);
fos.write(by2);
fos.close();
3. 通过FileInputStream、FileOutputStream实现图片的复制
File Srcfile = new File("text.txt");
File Destfile = new File("C:\\Users\\mwz\\Desktop\\copytxt.txt");
FileInputStream fis=new FileInputStream(Srcfile);
FileOutputStream fos = new FileOutputStream(Destfile);
byte[] buf=new byte[1024];
int len;
while((len=fis.read(buf))!=-1)
fos.write(buf,0,len);
fis.close();
fos.close();