1,Java中操作方法:
import java.io.*; public class FileInputStreamTest { public static void main(String[] args) throws IOException { //創建字節輸入流FileInputStream fis = new FileInputStream("FileInputStreamTest.java"); //創建一個長度為1024的竹筒byte[] bbuf = new byte[1024]; //用於保存實際讀取的字節數int hasRead = 0; //使用循環來重複“取水”的過程while((hasRead = fis.read(bbuf))>0) { //取出"竹筒"中(字節),將字節數組轉成字符串輸入System.out.println(new String(bbuf,0,hasRead)); } fis.close(); } } import java.io.*; public class FileReaderTest { public static void main(String[] args) throws IOException { FileReader fr = null; try { //創建字符輸入流fr = new FileReader("FileReaderTest.java"); //創建一個長度為32的"竹筒" char[] cbuf = new char[32]; //用於保存實際讀取的字符數int hasRead = 0; //使用循環來重複“取水”的過程while((hasRead = fr.read(cbuf))>0) { //取出"竹筒"中(字節),將字節數組轉成字符串輸入System.out.println(new String(cbuf,0,hasRead)); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { //關閉文件輸入流if(fr != null) { fr.close(); } } } }2,C#中操作方法:
/* - - - - - - - - - - - - - - - - - - - - - - - - * Stream 和byte[] 之間的轉換* - - - - - - - - - - - - - - - - - - - - - - - */ /// <summary> /// 將Stream 轉成byte[] /// </summary> public byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 設置當前流的位置為流的開始stream.Seek(0, SeekOrigin.Begin); return bytes; } /// <summary> /// 將byte[] 轉成Stream /// </summary> public Stream BytesToStream(byte[] bytes) { Stream stream = new MemoryStream(bytes); return stream; } /* - - - - - - - - - - - - - - - - - - - - - - - - * Stream 和文件之間的轉換* - - - - - - - - - - - - - - - - - - - - - - - */ /// <summary> /// 將Stream 寫入文件/// </summary> public void StreamToFile(Stream stream,string fileName) { // 把Stream 轉換成byte[] byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 設置當前流的位置為流的開始stream.Seek(0, SeekOrigin.Begin); // 把byte[] 寫入文件FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); } /// <summary> /// 從文件讀取Stream /// </summary> public Stream FileToStream(string fileName) { // 打開文件FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); // 讀取文件的byte[] byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); fileStream.Close(); // 把byte[] 轉換成Stream Stream stream = new MemoryStream(bytes); return stream; }以上就是小編為大家帶來的Java和C#輸入輸出流的方法(詳解)全部內容了,希望大家多多支持武林網~