FileOutputStream常用方法:
public void write(int b) //将指定字节写入此文件输出流
public void write(byte[] b) //将b.length个字节从指定byte 数组写入此文件输出流中
public void write(byte[] b,int off,int len) //将指定byte数组中从偏移量off开始的len个字节写入此文件输出流
public void close() //关闭此文件输出流并释放与此流有关的所有系统资源
使用write(int b)方法向score.txt文件写入数据:
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("java_stream\\score.txt");
fos.write(50);
fos.write('a');
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
可以看到存入文件中的内容并不是我们输入的数据,这是因为编码的一些原因造成的,若将数据再输出,可以看到还是我们当时存入时的数据:
try {
FileOutputStream fos = new FileOutputStream("java_stream\\score.txt");
FileInputStream fis = new FileInputStream("java_stream\\score.txt");
fos.write(50);
fos.write('a');
System.out.println(fis.read());
System.out.println((char)fis.read());
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
50
a
若写成FileOutputStream fos = new FileOutputStream("java_stream\\score.txt", true);
表示以追加的方式写入文件,而不是覆盖。
图片的读写和文件类似:
实现一个拷贝图片的过程。
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("java_stream\\animal.jpg");
FileOutputStream fos = new FileOutputStream("java_stream\\animalcopy.jpg");
byte[] b = new byte[1024];
int n = 0;
while((n = fis.read(b)) != -1){
fos.write(b);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}