Java 无法打开文件"/mnt/sdcard/test.txt“;
我一直因为找不到文件而出错。 我使用android模拟器来模拟代码 java.io.FileNotFoundException:/mnt/sdcard/test.txt:打开失败: EACCES(权限被拒绝)打开失败 请帮忙。。谢谢Java 无法打开文件"/mnt/sdcard/test.txt“;,java,android,Java,Android,我一直因为找不到文件而出错。 我使用android模拟器来模拟代码 java.io.FileNotFoundException:/mnt/sdcard/test.txt:打开失败: EACCES(权限被拒绝)打开失败 请帮忙。。谢谢 public class TestUpload extends Activity { /** Called when the activity is first created. */ @Override public void onCr
public class TestUpload extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_upload);
final TextView tmp = (TextView) findViewById(R.id.textView1);
tmp.setText("Hi! Click the button!");
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
File f = new File("/mnt/sdcard/test.txt");
try {
f.createNewFile();
Date d = new Date();
PrintWriter writer = new PrintWriter(f);
writer.println(d.toString());
writer.close();
HttpClient client = new DefaultHttpClient();
httpPostFileUpload(client, "/mnt/sdcard/test.txt", "http://localhost/upload.php", "uploadedfile");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void httpPostFileUpload(HttpClient client,String filePath,String uploadUri,String inputNameAttr) throws ClientProtocolException,IOException {
HttpUriRequest request = new HttpPost(uploadUri);
MultipartEntity form = new MultipartEntity();
client.getParams().setBooleanParameter("http.protocol.expect-continue", false);
form.addPart(inputNameAttr, new FileBody(new File(filePath)));
((HttpEntityEnclosingRequestBase) request).setEntity(form);
try {
client.execute(request);
} catch (ClientProtocolException e) {
throw e;
} catch (IOException ee) {
throw ee;
}
}
}
在yout manifest.xml中添加此行:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后,您将能够在外部存储器中进行写入。使用以下方法:
String file = Environment.getExternalStorageDirectory()+"/test.txt";
File f = new File(file);
if(f.exists()){
f.createNewFile();
}
// your code...
还可以在android清单文件中添加以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我猜您正在使用Android,因此我添加了Android标记。检查您是否在模拟器上声明了一些SD卡存储空间。另请查看您是否在ANDROID manifest中提到了使用外部存储的权限。请尝试字符串path=Environment.getExternalStorageDirectory().getAbsolutePath();文件f=新文件(路径+“/test.txt”);是的,我已经在模拟器上添加了SD卡存储空间!外部存储的权限。。。尚未声明可能的重复,我已更改为字符串file=Environment.getExternalStorageDirectory()+“/test.txt”;现在我打开失败:enoint(没有这样的文件或目录)