如何通过Socket将文件从服务器传输到Android手机并保持其格式。可以是任何类型的文件,例如pdf、html、png、txt等。我想要把这个文件从服务器推送到Android手机上,但在手机端保存文件时,我想知道来自服务器的文件格式。那么应该怎么做呢?
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
@Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
String name = "test";
File file = new File(
Environment.getExternalStorageDirectory(),
name);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
byte[] bytes;
FileOutputStream fos = null;
try {
bytes = (byte[])ois.readObject();
fos = new FileOutputStream(file);
fos.write(bytes);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fos!=null){
fos.close();
}
}
socket.close();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,
"Finished",
Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
这是客户端 我想知道如何获取从服务器发送的文件的文件格式
String name = "test";
File file = new File(
Environment.getExternalStorageDirectory(),
name);
想要了解如何查找服务器发送的文件格式。来自服务器的文件可能是HTML、PNG或TXT文件。
服务器端相关代码:
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
File file = new File(
Environment.getExternalStorageDirectory(),
"test.png");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(bytes);
oos.flush();
socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,
sentMsg,
Toast.LENGTH_LONG).show();
}
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
File file = new File(
Environment.getExternalStorageDirectory(),
"test.png");
test.png 文件可能有 png、html、txt 等扩展名。那么,有没有办法发送扩展名呢?
File.getName()
吗? - Emil