我想上传一个文本文件,我正在使用org.apache.commons.net.ftp.FTPclient
。代码每次都失败。
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("192.168.43.164",21);
client.login("android", "android");
client.setFileType(FTP.BINARY_FILE_TYPE);
client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
String filename = "/sdcard/m.txt";
fis = new FileInputStream(filename);
client.setFileType(FTP.BINARY_FILE_TYPE);
client.storeFile("/web/m.txt", fis);
fis.close();
client.logout();
} catch (IOException e) {
e.printStackTrace();
}
我正在关注本教程:FTP File Upload From Sdcard to server
Logcat输出,
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vaibhav.myapplication/com.example.vaibhav.myapplication.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
答案 0 :(得分:0)
FTPClient上传文件..为我工作
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.apache.commons.net.ftp.*;
import java.io.FileInputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new uploadTask().execute();
}
class uploadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("192.168.43.164", 21);
client.login("android", "android");
client.setFileType(FTP.BINARY_FILE_TYPE);
client.enterLocalPassiveMode();
client.sendCommand("OPTS UTF8 ON");
String filename = "/sdcard/m.txt";
fis = new FileInputStream(filename);
client.storeFile("/a/m.txt", fis);
fis.close();
client.logout();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}