// FileOutputStream 文件字節流輸出 public void FileOutputStreamTest1() throws IOException { // 1.使用File找到一個文件 File file = new File("f:" + File.separator + "cnn.txt"); // 2.經過子類實例化父類對象 OutputStream out = null; out = new FileOutputStream(file); // // 3.進行讀寫 String str = "Hello World!"; byte[] bt = str.getBytes();// 只能輸出字節數組 out.write(bt); // 關閉輸出流 out.close(); } // FileOutputStream 文件字節流輸出 public void FileOutputStreamTest2() throws IOException { // 1.使用File找到一個文件 File file = new File("f:" + File.separator + "cnn.txt"); // 2.經過子類實例化父類對象 OutputStream out = null; out = new FileOutputStream(file); // 3.進行讀寫 String str = "Hello World!"; byte[] bt = str.getBytes();// 只能輸出字節數組 for (int i = 0; i < bt.length; i++) { out.write(bt[i]); } // 關閉輸出流 out.close(); } //FileInputStream 文件字節輸入流 public void FileInputStreamDemo1() throws IOException { // 1使用File類找到文件 File f = new File("f:" + File.separator + "cnn.txt"); // 2.經過子類實例化父類對象 InputStream in = null;// 準備好一個輸入的對象 in = new FileInputStream(f); // 3.進行讀寫 byte[] bt = new byte[1024]; int len = 0; int temp = 0; while ((temp = in.read()) != -1) { bt[len] = (byte) temp; len++; } // 4.關閉輸入流 in.close(); } // 字節流轉化爲字符流 public void OutputStreamWriterDemo1() throws IOException { File f = new File("f:" + File.separator + "cnn.txt"); Writer out = null; out = new OutputStreamWriter(new FileOutputStream(f)); out.write("Hello World"); out.close(); } public void InputStreamReaderDemo1() throws IOException { File f = new File("f:" + File.separator + "cnn.txt"); Reader in = null; in = new InputStreamReader(new FileInputStream(f)); char[] c = new char[1024]; int len = in.read(c);// 讀取 in.close(); // 關閉 } // 內存流讀寫 public void ByteArraryDemo() throws IOException { String str = "HELLOWORLD!"; ByteArrayInputStream bis = null;// 內存輸入流 ByteArrayOutputStream bos = null;// 內存輸出流 bis = new ByteArrayInputStream(str.getBytes()); // 向內存中輸入內容 bos = new ByteArrayOutputStream(); // 準備從ByteArrayInputStream讀取內容 int temp = 0; while ((temp = bis.read()) != -1) { char c = (char) temp; // 讀取數字變成字符 bos.write(Character.toLowerCase(c)); // 轉換小寫 } bis.close(); bos.close(); String newStr = bos.toString(); System.out.println(newStr); } // BufferedReader 從字符輸入流中讀取文本,緩衝各個字符,從而實現字符、數組和行的高效讀取 public void BufferedReaderDemo() throws IOException { BufferedReader bf = null; // 聲明BufferedReader對象 // 1.System.in 字節輸入流 // 2.new InputStreamReader(System.in) 將字節輸入流,轉換爲字符輸入流 // 3.new BufferedReader(new InputStreamReader(System.in)) 將字符流緩衝到緩衝區 bf = new BufferedReader(new InputStreamReader(System.in)); String str = null; System.out.println("請輸入內容:"); str = bf.readLine(); System.out.println("輸入的內容是:" + str); }
FileOutputStream : out(byte[])和out(int)方法。java