1,Java中操作方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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(); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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#中操作方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
/* - - - - - - - - - - - - - - - - - - - - - - - - * 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#輸入輸出流的方法(詳解)全部內容了,希望大家多多支持服務器之家~