package java基础;
import java.io.*;
public class TestFileOutputStream {
public static void main(String[] args) {
// 在新建一个文件夹test,下面放一个文件:TestFileOutputStream.java
// 把该文件读取到内存
FileInputStream in = null;
FileOutputStream out = null;
try {
//方法1
in = new FileInputStream("D:" + File.separator + "test"+ File.separator +"TestFileOutputStream.java");
// int b = 0;
// while ((b = in.read()) != -1) {
// char c = (char)b;
// //System.out.print(c);//中文会有乱码
// }
//方法2
byte[] bytes = new byte[4096];
StringBuilder sb = new StringBuilder();//如果是单线程程序,比StringBuffer效率高
for(int n;(n=in.read(bytes))!=-1;) {//读取一些字节流到bytes里,并返回实际读取的字节数
sb.append(new String(bytes,0,n,"GBK"));//解决文件中的中文,输出乱码的情况
//把内存里的文件写入到硬盘的某个文件里,D:\test\haha.java
//haha.java目前在D:\test\下还没有,则要新建出来
out = new FileOutputStream("D:"+File.separator+"test"+File.separator+"haha.java");
out.write(bytes, 0, n);
}
//System.out.println(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}