转移后打开文件

时间:2014-10-09 21:05:43

标签: java file transfer

我想知道是否可以在java中执行此操作。这是我的代码:

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class SimpleFileClient {
    public final static int SOCKET_PORT = 13267;      // you may change this
    public final static String SERVER = "192.168.0.36";  // localhost
    public final static String
       FILE_TO_RECEIVED = "c:/temps/source-downloaded.mp3";  // you may change this, I give a
                                                        // different name because i don't want to
                                                        // overwrite the one used by server...

    public final static int FILE_SIZE = 6022386; // file size temporary hard coded
                                               // should bigger than the file to be downloaded

    public static void main (String [] args ) throws IOException {
        int bytesRead;
        int current = 0;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        Socket sock = null;
        try {
          sock = new Socket(SERVER, SOCKET_PORT);
          System.out.println("Connecting...");

          // receive file
          byte [] mybytearray  = new byte [FILE_SIZE];
          InputStream is = sock.getInputStream();
          fos = new FileOutputStream(FILE_TO_RECEIVED);
          bos = new BufferedOutputStream(fos);
          bytesRead = is.read(mybytearray,0,mybytearray.length);
          current = bytesRead;

          do {
             bytesRead =
                is.read(mybytearray, current, (mybytearray.length-current));
             if(bytesRead >= 0) current += bytesRead;
          } while(bytesRead > -1);

          bos.write(mybytearray, 0 , current);
          bos.flush();
          System.out.println("File " + FILE_TO_RECEIVED
              + " downloaded (" + current + " bytes read)");
        }
        finally {
          if (fos != null) fos.close();
          if (bos != null) bos.close();
          if (sock != null) sock.close();
        }
    }
}

我想知道文件是否可以在传输完成后打开。谢谢你的回答。

0 个答案:

没有答案