Java流的理解

最近做了一下Socket编程,其中有socket.getInputStream和socket.getOutputStream的问题。

想传输文件,感觉应该用FileInputStream和FileOutputStream。但是他们的构造函数是这样的:

  

  FileOutputStream fos = new FileOutputStream("e:\o.txt",true);
   FileInputStream fis = new FileInputStream("e:\o.txt");

实际上,流中设定的文件名的含义是  从这个文件中取,或向这个文件中写  的意思。

所以,socket.getInputStream获得的流可以从中读取东西。

    socket.getOutputStream获得的流可以往里面些东西。

先举个例子:

//先将byte b[]的数值存入e:/o.txt,再读取o.txt显示出来。
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;
public class E_FileOutputStream1 { /** * @param args */ public static void main(String[] args) { byte b [] = {49,50,97,98}; try { FileOutputStream fos = new FileOutputStream("e:\o.txt",true); FileInputStream fis = new FileInputStream("e:\o.txt"); for(int i = 0; i<b.length ; i++) fos.write(b[i]); int c = fis.read(); while(c != -1){ System.out.println(c); c = fis.read(); } fos.close(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } } }

所以两个socket进行文件传输的话,可以这样实现:

原文地址:https://www.cnblogs.com/wangjiyuan/p/filechuanshu.html