Java和C#输入输出流的方法(详解)
1,Java中操作方法:
importjava.io.*;
publicclassFileInputStreamTest
{
publicstaticvoidmain(String[]args)throwsIOException
{
//创建字节输入流
FileInputStreamfis=newFileInputStream("FileInputStreamTest.java");
//创建一个长度为1024的竹筒
byte[]bbuf=newbyte[1024];
//用于保存实际读取的字节数
inthasRead=0;
//使用循环来重复“取水”的过程
while((hasRead=fis.read(bbuf))>0)
{
//取出"竹筒"中(字节),将字节数组转成字符串输入
System.out.println(newString(bbuf,0,hasRead));
}
fis.close();
}
}
importjava.io.*;
publicclassFileReaderTest
{
publicstaticvoidmain(String[]args)throwsIOException
{
FileReaderfr=null;
try
{
//创建字符输入流
fr=newFileReader("FileReaderTest.java");
//创建一个长度为32的"竹筒"
char[]cbuf=newchar[32];
//用于保存实际读取的字符数
inthasRead=0;
//使用循环来重复“取水”的过程
while((hasRead=fr.read(cbuf))>0)
{
//取出"竹筒"中(字节),将字节数组转成字符串输入
System.out.println(newString(cbuf,0,hasRead));
}
}
catch(IOExceptionioe)
{
ioe.printStackTrace();
}
finally
{
//关闭文件输入流
if(fr!=null)
{
fr.close();
}
}
}
}
2,C#中操作方法:
/*------------------------
*Stream和byte[]之间的转换
*-----------------------*/
///<summary>
///将Stream转成byte[]
///</summary>
publicbyte[]StreamToBytes(Streamstream)
{
byte[]bytes=newbyte[stream.Length];
stream.Read(bytes,0,bytes.Length);
//设置当前流的位置为流的开始
stream.Seek(0,SeekOrigin.Begin);
returnbytes;
}
///<summary>
///将byte[]转成Stream
///</summary>
publicStreamBytesToStream(byte[]bytes)
{
Streamstream=newMemoryStream(bytes);
returnstream;
}
/*------------------------
*Stream和文件之间的转换
*-----------------------*/
///<summary>
///将Stream写入文件
///</summary>
publicvoidStreamToFile(Streamstream,stringfileName)
{
//把Stream转换成byte[]
byte[]bytes=newbyte[stream.Length];
stream.Read(bytes,0,bytes.Length);
//设置当前流的位置为流的开始
stream.Seek(0,SeekOrigin.Begin);
//把byte[]写入文件
FileStreamfs=newFileStream(fileName,FileMode.Create);
BinaryWriterbw=newBinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
}
///<summary>
///从文件读取Stream
///</summary>
publicStreamFileToStream(stringfileName)
{
//打开文件
FileStreamfileStream=newFileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read);
//读取文件的byte[]
byte[]bytes=newbyte[fileStream.Length];
fileStream.Read(bytes,0,bytes.Length);
fileStream.Close();
//把byte[]转换成Stream
Streamstream=newMemoryStream(bytes);
returnstream;
}
以上就是小编为大家带来的Java和C#输入输出流的方法(详解)全部内容了,希望大家多多支持毛票票~