测试代码很多都是写死的,实际使用中将其动态化即可
FileOutputStream 写入文件
public static void testStreamWrite() throws IOException {
//创建字节流输出对象
FileOutputStream fileOutputStream = new FileOutputStream("byteStream.txt");
//把内容直接写到了目的文件中
fileOutputStream.write("abcd".getBytes());
//关闭流对象
fileOutputStream.close();
}
FileInputStream 读取文件
public static void testStreamRead() throws IOException {
//创建字节流输入对象
FileInputStream fileInputStream = new FileInputStream("byteStream.txt");
//这里读取英文是没有问题的,但是如果是中文,则会出现乱码
int ch=0;
while((ch=fileInputStream.read())!=-1){
System.out.println("ch = " + (char)ch);
}
fileInputStream.close();
}
FileInputStream 读取文件byte[]
public static void testStreamReadArr() throws IOException {
//创建字节流输入对象
FileInputStream fileInputStream = new FileInputStream("byteStream.txt");
//这里读取英文是没有问题的,但是如果是中文,则会出现乱码
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(bytes)) != -1) {
System.out.println("ch = " + new String(bytes,0,len));
}
fileInputStream.close();
}
使用字节流复制文件(图片)
这样的复制文件的方式可以是任意格式的文件
复制文件时,千万不要读取一个字节写入一个字节,效率奇低
public static void copyFile() throws IOException {
FileInputStream fileInputStream = new FileInputStream("image.jpg");
FileOutputStream fileOutputStream = new FileOutputStream("image_copy.jpg");
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes,0,len);
}
fileInputStream.close();
fileOutputStream.close();
}
使用缓冲区复制文件(图片)
这样的复制文件的方式可以是任意格式的文件
public static void copyFile2() throws IOException {
//定义文件输入流关联一个文件
FileInputStream fileInputStream = new FileInputStream("image.jpg");
//定义输入流缓冲区管理一个输入流对象
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
//定义一个输出流对象,关联一个文件
FileOutputStream fileOutputStream = new FileOutputStream("image_copy.jpg");
//定义一个输出流缓冲区,管理一个输出流对象
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte[] bytes = new byte[1024];
int len = 0;
//从输入流缓冲区中读取文件内容
while ((len = bufferedInputStream.read(bytes)) != -1) {
//通过输出流缓冲区将读取的内容写入到输出流关联的文件中
bufferedOutputStream.write(bytes,0,len);
}
bufferedInputStream.close();
bufferedOutputStream.close();
}