在学习网络之前,学习本地的数据流转时很有必要。应为到了接触网络传输的时候,会发现,我们的学习的机制是一样的。所以,我打算写记录下标准IO
1、如何获取键盘输入并输出(read,write)
byte[] buffer =new byte[1024];
while(true)
{
int n=System.in.read(buffer);//将键盘输入保存到buffer中并返回n;
System.out.write(buffer,0,n);//write从buffer中将0-n数据输出至显示器
}
要点:此处要理解的是,in.read<--->out.write之间的联系。in和out都是相对内存来讲的
2、将所获得的键盘输入输出至文件(FileOutputStream)
此处我们要做的就是讲标准输入输出流(IO)写到文件流里面去
byte[] buffer=new byte[1024];
FileOutputStream outfile=null;
outfile=new FileOutputStream(arg[0]);
int n=System.in.read(buffer);
outfile.write(buffer,0,n);
要点:以上两个例子都是先将数据读到byte[1024]数组里面,再进行或者IO或者FileOutputSteam的操作
3、从文件中读取数据(FileInputStream)
byte[] buffer =new byte[1024];
FileInputStream infile =null;
infile =new FileInputStream(args[0]);
int n=inflie.read(buffer);
System.out.write(buffer,0,n);
要点:此处要做的对比的是,我们利用了infile =new FileInputStream(args[0]);已经获取了文本数据作为数据源,我们用infile.read()函数将数据读入buffer中并返回n。
以上就是基本的数据在IO 和FIle 之间的转换的方法,也为接下来的网路数据传输打下基础。记住,后面的网络数据传输跟以上上个的原理非常相似。不同的只是换了数据源而已。