简体   繁体   English

Android:无法在文本文件上写字符串

[英]Android: can't write a string on a text file

I have problem with the writing of a file. 我在写文件时遇到问题。 My app simply takes a file from sd card, write a string on it and uplod this file to a server ftp. 我的应用程序只是从SD卡中提取一个文件,在其中写入一个字符串,然后将此文件上传到服务器ftp。 The uploading of the file is perfect, but I can't write the string on the file, i've tried the writing of the string in a lot of way but no one worked. 文件的上传是完美的,但是我不能在文件上写字符串,我已经尝试了很多方式写字符串,但是没有人工作。 This is my code, Main and FTPUpload 这是我的代码,主要和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);
}

} }

FTPupload: 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);
}

} }

I've tried differt way of writing on file, for example: 我尝试了不同的文件写入方式,例如:

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

or: 要么:

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());
} 

I add two permission : 我添加两个权限:

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

NB: the app give NO errors, and the upload of the file on the server works properly 注意:应用程序没有错误,并且服务器上的文件上传正常

Have you tried with a BufferedWriter instead of OutputStreamWriter? 您是否尝试过使用BufferedWriter而不是OutputStreamWriter? That worked for me (wasn't on Android though, but give it a go and see if it works :) 这对我有用(虽然不是在Android上,但是试一试,看看是否可行:)

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

And remember to close it afterwards 并记得之后将其关闭

bw.close();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM