FileInputStream和FileOutputStream:用于磁盘、光盘或其他存储设备中文件的字节流的读写
1 从文件系统中读取文件到程序(内存中)
example1:(FileInputStream从文件系统中读取字节)
package com.yxstudy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ByteReader{
public static void main(String[] args) {
// TODO Auto-generated method stub
char seq = File.separatorChar;//这种方式适用于任何操作系统
try {
FileInputStream fis = new FileInputStream("D:"+seq+"temp"+seq+"1-130G409554O34.jpg");//
boolean eof = false;//是否到达文件末尾
byte[] buffer = new byte[512];//每次读取的字节
int count = 0;
while (!eof) {
int input = fis.read(buffer, 0, buffer.length);
System.out.print(input+ " ");
if (input==-1)
eof = true;//如果到达文件末尾,则将此标志赋值为true,退出while循环。
else
count++; //记录读取的次数
}
fis.close();//释放资源
System.out.println("\nBytes array readCount: " + count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error --" + e.toString());
}
}
}
example2: 先把文件读到内存中在输出到文件系统其他文件夹(文件输出流中)
package com.yxstudy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteWriter {
public static void main(String[] args) {
// TODO Auto-generated method stub
char seq = File.separatorChar;
try {
FileInputStream fis = new FileInputStream("D:"+seq+"temp"+seq+"1-130G409554O34.jpg");
FileOutputStream fos = new FileOutputStream("D:"+seq+"temp_dst"+seq+"copy.jpg");//temp_dst目录必须存在
byte[] buff = new byte[1024];
int length = 0;
while((length = fis.read(buff))!=-1){
fos.write(buff, 0, length);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error --" + e.toString());
}
}
}