Java和C#輸出輸入流的辦法(詳解)。本站提示廣大學習愛好者:(Java和C#輸出輸入流的辦法(詳解))文章只能為提供參考,不一定能成為您想要的結果。以下是Java和C#輸出輸入流的辦法(詳解)正文
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#輸出輸入流的辦法(詳解)全體內容了,願望年夜家多多支撐~