java IO--字元流的輸入輸出
阿新 • • 發佈:2019-02-17
/** * ClassName: CharStreamDemo * 字元流: * 字元輸出流:Writer,對檔案的操作 使用子類:FileWriter * 字元輸入流:Reader,對檔案的操作使用子類:FileReader * 每次操作的單位是一個字元 * 內部實現還是位元組流 * 檔案字元操作流會自帶快取,預設大小為1024位元組,在快取滿後,或手動重新整理快取,或關閉流時會把資料寫入檔案 * * 操作非文字檔案時使用位元組流,操作文字檔案時使用字元流方便一些 * @author cai * @date 2018年10月16日 */ public class CharStreamDemo { private static void out() { File file = new File("C:\\Users\\Desktop\\需要被刪的\\ffff\\新建文字文件.txt"); try { Writer out = new FileWriter(file,true); out.write("\\n明天上證指數100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); out.close(); } catch (IOException e) { e.printStackTrace(); } } private static void in() { File file1 = new File("C:\\Users\\Desktop\\需要被刪的\\ffff\\新建文字文件.txt"); try { Reader in = new FileReader(file1); char[] cs = new char[1]; int len = -1; StringBuilder buf= new StringBuilder(); while((len = in.read(cs))!=-1) { buf.append(new String(cs,0,len)); } in.close(); System.out.println(buf); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { out(); in(); } }