我正在创建一个简单的文件传输应用程序。将所选文件从一个设备发送到另一个设备。如果我知道要接收的文件名,它工作正常。
但如果我不知道文件名,那么就不会使用FileOutputStream
在指定位置写入文件。
这是我的代码:
发件人:
try {
// create socket
// TODO: the port should match the one in Client
ServerSocket servsock = new ServerSocket(5005);
while (true) {
Log.i("************", "Waiting...");
Socket sock = servsock.accept(); // blocks until connection opened
Log.i("************", "Accepted connection : " + sock);
// sendfile
// TODO: put the source of the file
File myFile = new File ("/mnt/sdcard/download/1.html");
byte [] mybytearray = new byte [(int)myFile.length()];
Log.i("####### file length = ", String.valueOf(myFile.length()) );
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
String text = "1.html";
byte[] bytes = text.getBytes("UTF-8");
os.write(bytes);
Log.i("************", "Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
} catch (IOException e) {
Log.i("Io execption ", "e: " + e);
}
在发件人代码中,我已经指定了要发送给其他设备的文件。这是1.html
,使用这一行:
File myFile = new File ("/mnt/sdcard/download/1.html");
以下是我的接收者代码:
try {
int filesize=900000; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
// TODO: server's IP address. Socket should match one above in server
Socket sock = new Socket("192.168.43.139",5005);
Log.i("************", "Connecting...");
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
// TODO: Put where you want to save the file
/* N.B.:
* * To view if the file transfer was successful:
* * use `./adb shell`
* * use the app: File Manager
*
* * If you downloaded to '/mnt/sdcard/download',
* your download might not show up in 'Downloads'
*
* * You might not have '/mnt/sdcard/download' directory
* if you have never downloaded anything on your iPhone
*/
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/download/1.html");
BufferedOutputStream 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();
long end = System.currentTimeMillis();
Log.i("** end-start = ", String.valueOf(end-start));
bos.close();
sock.close();
} catch ( UnknownHostException e ) {
Log.i("******* :( ", "UnknownHostException");
} catch (IOException e){
Log.i("Read has IOException", "e: " + e);
}
仅当我将FileOutputStream
设置为1.html
时,才会存储已接收的文件。否则它不会被保存。
那么我该如何让这个过程变得动态。我的意思是,我可以保存发件人发送的任何文件,而不知道其确切名称的类型?
如果我向接收者提供文件名,此代码工作正常。
供参考,我正在关注this教程或代码。
请帮忙!谢谢!