一、字节流读文件方法:
示例:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("text.txt");// 生成一个输入流
byte input[] = new byte[21];// 生成字节数组
fis.read(input);// 将文件数据读取到字节数组中
String inputString = new String(input, "UTF-8");
System.out.println(inputString);
fis.close();//记得关闭
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
结果:
字节流写文件方法:
示例:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteByteStream {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("textw.txt");
String outString = "write 123456写出数据";
byte output[] = outString.getBytes("UTF-8");
fos.write(output);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
结果:
3.利用字节流读写来实现文件拷贝
示例:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyByByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("1.jpg");
FileOutputStream fos = new FileOutputStream("1_copy.jpg");
byte input[] = new byte[50];
//bytes[50]不够存储图片,所以要用while
while (fis.read(input) != -1) {
fos.write(input);
}
fis.close();
fos.close();
System.out.println("done");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
结果:
拷贝出一个.jpg文件