【发布时间】:2015-09-08 04:22:39
【问题描述】:
如何使用 Socket 将文件从服务器传输到 Android Mobile 并保持其格式。它可以是任何文件,例如 pdf、html、png、txt 等。我想将此文件从服务器推送到 Android Mobile,但在移动端保存文件时,我想知道来自服务器的文件的格式。那怎么办呢?
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 扩展名。那么有什么方法可以发送扩展名吗?
【问题讨论】:
-
我对 Sockets 了解不多,这就是我问的原因。
-
我已经问过 Google 这就是我来这里的原因
-
如果你帮不上忙,如果你不知道,那你为什么要评论并否决我的问题。
-
您的问题并不意味着特定问题,因此不会为您编码。你必须向我们展示你所做的一些努力。此外,我还不是还对你投反对票的人。 (我在帮你问正确的问题)
-
耶..你来了..你已经发布了一些代码。现在告诉我们您遇到了什么错误?