gpt4 book ai didi

java - 从 Android 应用程序写入文本文件时发生错误

转载 作者:行者123 更新时间:2023-12-01 18:44:14 25 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,我想写入一个文本文件。但单击写入按钮后,应用程序会向我显示一条错误消息并停止。错误是

IllegalArgumentException: File mnt/sdcard/test.txt contains a path separator

我使用了以下代码:

try {
final String TESTSTRING = new String("Hello Android");

FileOutputStream fOut = openFileOutput("mnt/sdcard/test.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);

osw.write(TESTSTRING);

osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}

最佳答案

确保您有:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" / > 也在你的 list 中。

 package com.example.fileio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class FilioActivity extends Activity {

private TextView tv;
private static final String TAG = "MEDIA";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);

CreateExternalLogFile("I am adding something into the text file!");
}

private void CreateExternalLogFile(String s){
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "filename.txt");
tv.append("\nExternal file system root: "+ dir);
try {
FileOutputStream f = new FileOutputStream(file,false); //True = Append to file, false = Overwrite
PrintStream p = new PrintStream(f);
p.print(s);
p.close();
f.close();


} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\nFile written to \n"+file);


}
}

关于java - 从 Android 应用程序写入文本文件时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18539739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com