FileOutputStream
基本写数据
FileOutputStream fos = new FileOutputStream("idea_test\\src\\com\\FIle\\fos.txt",true);
fos.write(97);
byte[] bys = {23,43,23,53,32,54};
fos.write(bys);
fos.write("\n".getBytes());
byte[] bys2 = "JYQWBD".getBytes();
fos.write(bys2,1,3);
fos.close();
异常处理
FileOutputStream ofs = null;
try {
ofs = new FileOutputStream("idea_test\\\\src\\\\com\\\\FIle\\\\fos.txt");
ofs.write("hello".getBytes());
} catch (IOException e){
e.printStackTrace();
} finally {
if(ofs != null){
try {
ofs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileInputStream
读取单个字节
FileInputStream fis = new FileInputStream("idea_test\\\\src\\\\com\\\\FIle\\\\fos.txt");
int by = fis.read();
while(by!=-1){
System.out.print((char) by);
by = fis.read();
}
int by2 = 0;
while((by2=fis.read())!=-1){
System.out.println((char)by2);
}
fis.close();
读取一个字节数组的数据
FileInputStream fis = new FileInputStream("idea_test\\src\\com\\FIle\\fos.txt");
byte[] bys2 = new byte[1024];
int len2 = 0;
while((len2 = fis.read(bys2))!=-1){
System.out.println(new String(bys2,0,len2));
}
复制图片
FileInputStream fis = new FileInputStream("C:\\Users\\17822\\Desktop\\个人资料\\毕业.jpg");
FileOutputStream fos = new FileOutputStream("C:\\Users\\17822\\Desktop\\毕业2.jpg");
byte[] bys =new byte[1024];
int len = 0;
while((len = fis.read(bys))!=-1){
fos.write(bys,0,len);
}
fos.close();
fis.close();
|