【问题标题】:Android: can't write a string on a text fileAndroid:无法在文本文件上写入字符串
【发布时间】:2015-12-05 05:52:16
【问题描述】:

我在写入文件时遇到问题。我的应用程序只是从 sd 卡中获取一个文件,在其上写入一个字符串并将此文件上传到服务器 ftp。文件的上传是完美的,但是我不能在文件上写字符串,我已经尝试了很多方式的字符串的写入,但没有一个成功。 这是我的代码,Main 和 FTPUpload

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FtpUpload upload = new FtpUpload(handler,this);
    upload.execute();

}

private final Handler handler = new Handler() {
    public void handleMessage(Message message) {
        ArrayList result = (ArrayList) message.getData().get("data");

        for(Object fileName : result) {             
            Toast.makeText(getApplicationContext(), fileName.toString(), 
                    Toast.LENGTH_LONG).show();

        }
    }
};


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

FTP上传:

public class FtpUpload extends AsyncTask<Void, Void, ArrayList> {

private Handler handler;
private Context context;

public FtpUpload(Handler hand, Context context) {
    this.handler = hand;
    this.context = context;

}

@Override
protected ArrayList doInBackground(Void... params) {

    ArrayList files = new ArrayList();
    FTPClient mFTPClient = new FTPClient();

    boolean status = false;

    String filename = "prova.txt";
    String srcFilePath = "/mnt/extSdCard/Download/";
    try {
        mFTPClient.setConnectTimeout(10 * 1000);
        mFTPClient.connect(InetAddress.getByName("+++++++++++++"));
        status = mFTPClient.login("**********", "*********");
        mFTPClient.changeWorkingDirectory("/");
        mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
        mFTPClient.enterLocalPassiveMode();
        File file = new File(srcFilePath + filename);

        final String TESTSTRING = new String("AAAAAAAAAAAAAAA");


        try {
             final ByteArrayOutputStream baos = new ByteArrayOutputStream();
             baos.write(TESTSTRING.getBytes());
              final FileOutputStream fos = new FileOutputStream(file);
              fos.write(baos.toByteArray());
              fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        BufferedInputStream buffIn = null;
        buffIn = new BufferedInputStream(new FileInputStream(file), 8192);

        status = mFTPClient.storeFile(filename, buffIn);

    } catch (Exception e) {
    }

    return files;
}

@Override
protected void onPostExecute(ArrayList result) {
    Message message = handler.obtainMessage();
    Bundle bundle = new Bundle();
    bundle.putStringArrayList("data", result);
    message.setData(bundle);
    handler.sendMessage(message);
}

}

我尝试了不同的文件写入方式,例如:

 FileOutputStream dfdfd = new FileOutputStream(file);
 OutputStreamWriter osw = new OutputStreamWriter(dfdfd);
 osw.write(TESTSTRING)

或:

try {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(file.getName(), context.MODE_PRIVATE));
    outputStreamWriter.write(TESTSTRING);
    outputStreamWriter.close();
}
catch (IOException e) {
    Log.e("Exception", "File write failed: " + e.toString());
} 

我添加了两个权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

注意:应用程序没有错误,服务器上的文件上传正常

【问题讨论】:

    标签: java android file ftp filewriter


    【解决方案1】:

    您是否尝试过使用 BufferedWriter 而不是 OutputStreamWriter?这对我有用(虽然不是在 Android 上,但试一试,看看它是否有效 :)

    FileOutputStream dfdfd = new FileOutputStream(file);
    BufferedWriter bw = new BufferedWriter(dfdfd);
    bw.write(TESTSTRING);
    

    然后记得关闭它

    bw.close();
    

    【讨论】:

      【解决方案2】:

      我不认为将文件保存在 sdcard 上是正确的方法。 也许你应该尝试 context.getdirs() context.getfiledirs() 或 context.getcachedirs()。因为 Android 建议应用程序应该在 /sdcard/Android/packagenames/.. 中使用自己的 dirs

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-29
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        • 2011-05-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多