简体   繁体   中英

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. 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

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:

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? That worked for me (wasn't on Android though, but give it a go and see if it works :)

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 / ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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