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();
复制视频
long startTime = System.currentTimeMillis();
method4();
long endTime = System.currentTimeMillis();
System.out.println("共耗时:" + (endTime - startTime) + "ms");
}
public static void method1() throws IOException {
FileInputStream fis = new FileInputStream("idea_test\\src\\com\\FIle\\狗.mp4");
FileOutputStream fos = new FileOutputStream("idea_test\\src\\com\\FIle\\狗2.mp4");
int by = 0;
while ((by = fis.read()) != -1) {
fos.write(by);
}
fos.close();
fis.close();
}
public static void method2() throws IOException {
FileInputStream fis = new FileInputStream("idea_test\\src\\com\\FIle\\狗.mp4");
FileOutputStream fos = new FileOutputStream("idea_test\\src\\com\\FIle\\狗2.mp4");
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
fos.write(bys,0,len);
}
fos.close();
fis.close();
}
public static void method3() throws IOException{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("idea_test\\src\\com\\FIle\\狗.mp4"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("idea_test\\src\\com\\FIle\\狗2.mp4"));
int by =0;
while((by = bis.read())!=-1){
bos.write(by);
}
bos.close();
bis.close();
}
public static void method4() throws IOException{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("idea_test\\src\\com\\FIle\\狗.mp4"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("idea_test\\src\\com\\FIle\\狗2.mp4"));
byte[] bys = new byte[1024];
int len =0;
while((len = bis.read(bys))!=-1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}