inputstream輸入流
/** * 從文件中讀取數(shù)據(jù) * @param args * @throws Exception */ public static void main(String[] args)throws Exception { String filePath = "C:/Users/zwk/Desktop/1.txt"; InputStream in = new FileInputStream(filePath); //臨時存放讀取的數(shù)據(jù),若文件超出1024,多次讀取,每次讀取1024,直到讀取完成 //可以改變1024的大小,減少或增加讀取的次數(shù) byte[] b = new byte[1024]; int l; StringBuilder sb = new StringBuilder(); while ((l = in.read(b)) != -1){ //將讀取的子節(jié)數(shù)組轉(zhuǎn)換為字符串 sb.append(new String(b,0,l,"UTF-8")); } }
inputstream輸入流2
public static void main(String[] args)throws Exception { String filePath = "C:/Users/zwk/Desktop/2.txt"; InputStream in = new FileInputStream(filePath); //臨時存放讀取的數(shù)據(jù),若文件超出1024,多次讀取,每次讀取1024,直到讀取完成 //可以改變1024的大小,減少或增加讀取的次數(shù) byte[] b = new byte[1024]; int l; //讀取的長度 //StringBuilder sb = new StringBuilder(); //將讀取的數(shù)據(jù)存放到輸出緩存流中 ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((l = in.read(b)) != -1){ //將讀取的子節(jié)數(shù)組轉(zhuǎn)換為字符串 //sb.append(new String(b,0,l,"UTF-8")); //存放到輸出流中 bos.write(b,0 , l); } System.out.println(new String(bos.toByteArray(),0,bos.toByteArray().length,"utf-8")); }
輸出流輸入流
/** * 從文件中讀取數(shù)據(jù)并輸出到另外一個文件上 * @param args */ public static void main(String[] args) { //從文件中讀取 InputStream in = null; OutputStream out = null; try { String filePath = "C:/Users/zwk/Desktop/2.txt"; in = new FileInputStream(filePath); byte[] b = new byte[1024]; int l; StringBuilder sb = new StringBuilder(); while ((l = in.read(b)) != -1){ sb.append(new String(b,0,l,"UTF-8")); } //輸出到文件中 out = new FileOutputStream("C:/Users/zwk/Desktop/3.txt"); out.write(sb.toString().getBytes()); } catch (Exception e){ } finally { //關(guān)閉資源 if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
浙公網(wǎng)安備 33010602011771號