java IO 字節流最常用兩種讀寫方式
隨筆記錄
今天在看導入功能開發時順便動手敲了一下Java io字節流讀寫的代碼,感覺簡單,但是深刻理解還是需要話功夫研究,也在博客中mark一下,便於溫故知新
package com.gsww.jzfp.commons;
import java.io.*;
/**
* Description:java IO 流學習
*/
public class JavaIODeamo {
public static void main(String[] args) {
File file =new File("D:\\copy_nginx.conf");
try {
//getFileByOutPutStream(file);
getFileByBufferedOutPutStream(file);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 利用 字節流 讀取文件、寫入文件
* @param file
*/
private static void getFileByOutPutStream(File file) throws IOException {
//讀取文件
InputStream in = new FileInputStream(new File("D:\\nginx.conf"));
//寫出文件
//1、判斷文件是否存在
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
//2、定義輸出字節長度
byte[] bytes=new byte[2018];
int len= -1;
//3、循環輸出
while ((len = in.read(bytes,0,bytes.length))!=-1){
//轉換成字符串
String str = new String(bytes,0,len,"GBK");
System.out.println(str);
//輸出
out.write(bytes,0,len);
}
out.flush();
in.close();
out.close();
}
/**
* 利用 緩衝字節流 讀取文件、寫入文件
* @param file
*/
private static void getFileByBufferedOutPutStream(File file) throws IOException {
//讀取文件
BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("D:\\nginx.conf")));
//寫出文件
//1、判斷文件是否存在
if(!file.exists()){
file.createNewFile();
}
//2、輸出流
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
//定義字節長度
byte[] bytes = new byte[2048];
int len = -1;
//循環寫出
while ((len = in.read(bytes, 0, bytes.length)) != -1) {
//可以轉換字符流
String Str = new String(bytes, 0, len, "GBK");
System.out.println(Str);
//字節輸出
out.write(bytes,0,len);
}
out.flush();
in.close();
out.close();
}
}