[英]How to write a file to Android SD Card that is visible on PC
我试图在应用程序运行时将数据存储在文件中,以便在将数据连接到PC时轻松地将其从设备中删除。
现在,我可以创建文件并写入文件,但是我的计算机看不到该文件。
请注意,我真的不希望使用DDMS,因为我会要求经验有限的人这样做。
我知道它正在写入文件,因为我可以在设备的文件管理器上看到它。 如果将文件复制到设备上的另一个目录中,则可以在计算机上看到它,但这不是我所处情况的有效解决方法。
这是我所拥有的:
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();
}
感谢您的时间。
尝试添加file.createNewFile();
File file = new File(dir, fileName + ".csv");
file.createNewFile();
以下示例将在Android外部存储根目录中创建一个名为“ 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;
}
}
如果外部存储设备不可用,则对getExternalStorageDirectory()的调用将失败。 有关详细信息,请参见getExternalStorageDirectory() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.