I am trying to store data in a file while my application is running in order to easily get it off of the device when I connect it to a PC.
Right now, I am able to create the file and write to it, but my computer cannot see the file.
Note that I would really prefer not to use DDMS as I will be asking people with limited experience to do this.
I know it is writing the file, as I can see it on the device's file manager. If I copy the file into another directory on the device, I can then see it on a computer, but this isn't a valid workaround for my situation.
Here is what I have:
String fileName = "test";
String stuffToWrite = "testString";
try
{
File sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File dir = new File (sdCard.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, fileName + ".csv");
file.setReadable(true,false);
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(stuffToWrite);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
}
Thank you for your time.
Try to add file.createNewFile();
File file = new File(dir, fileName + ".csv");
file.createNewFile();
The following example will create a file in the Android external storage root directory called "hello.txt":
package external.com;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class WriteExStorage extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String ex_storage_directory;
ex_storage_directory = Environment.getExternalStorageDirectory().toString();
File f = new File(ex_storage_directory, "hello.txt");
try
{
PrintWriter p = new PrintWriter(new FileWriter(f));
p.println("Hello External Storage!");
p.close();
}
catch(java.io.IOException e)
{
return;
}
}
The call to getExternalStorageDirectory() will fail if the external storage device is not available. See getExternalStorageDirectory() for details.
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.