详细 百度和文档
https://www.cnblogs.com/shitouer/archive/2012/12/19/2823641.html
1.
2.
3.
is = new FileInputStream("D://a/a/a.txt"); os = new FileOutputStream("D://a/b/a.txt"); //装东西的小桶 byte[] buffer = new byte[1024];
//byte[] buffer = new byte[1024*20];
int len; while((len = is.read(buffer)) != -1){ //从buffer的0开始,到len结束 os.write(buffer,0,len); }
/** * 拷贝文件 */ @Test public void copyFile() throws IOException { InputStream is = null; OutputStream os = null; try { // 1 is = new FileInputStream("D://a/a/a.txt"); os = new FileOutputStream("D://a/b/a.txt"); //装东西的小桶 byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){ //从buffer的0开始,到len结束 os.write(buffer,0,len); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { // 2 if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } //3 if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }
File file = new File("D://a/a/a.txt"); long length = file.length(); //一次20k int per = 1024*20; //已经拷贝完成的大小 long completed = 0L; long currentProgress = 0L; is = new FileInputStream("D://a/a/a.txt"); os = new FileOutputStream("D://a/b/a.txt"); //装东西的小桶 byte[] buffer = new byte[per]; int len; while((len = is.read(buffer)) != -1){ //从buffer的0开始,到len结束 os.write(buffer,0,len); completed += per; //显示进度 double percent = (((double)completed/(double) length)*100); long progress = Math.round(percent); if (progress != currentProgress){ System.out.println("已经拷贝了:"+ progress + "%"); } currentProgress = progress; }
4. 读文件
//放一个管道到文件上
//整一个缓冲
//写出去
/** * 读文件 * @throws Exception */ @Test public void readFile() throws Exception { InputStream is = new FileInputStream("D://a.txt"); byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){ String s = new String(buffer, 0,len); System.out.println(s); } is.close(); }
/** * 读文件 * @throws Exception */ @Test public void readFile() throws Exception { Reader reader = new FileReader("D://a.txt"); char[] buffer = new char[1024]; int len; while((len = reader.read(buffer)) != -1){ String s = new String(buffer, 0,len); System.out.println(s); } reader.close(); }
字节流可以处理任何字符流的东西。
/** * 读文件 * @throws Exception */ @Test public void readFile() throws Exception { Reader reader = new FileReader("D://a.txt"); BufferedReader bf = new BufferedReader(reader); String str; while ((str = bf.readLine()) != null){ System.out.println(str); } reader.close(); }
处理流 一行一行的读
5. 写文件
@Test public void writeFile() throws Exception{ //放一个管道到文件上 FileOutputStream fo = new FileOutputStream("D://a.txt"); String str = "hello World"; //写出去 fo.write(str.getBytes(StandardCharsets.UTF_8)); fo.flush(); fo.close(); }
@Test public void writeFile() throws Exception{ //放一个管道到文件上 FileWriter fw = new FileWriter("D://a.txt"); String str = "hello World"; //写出去 fw.write(str); fw.flush(); fw.close(); }
fw.append("aa").append("bb");