创建文本文件 Android IO
我正在尝试在 Android 手机上创建一个文本文件,并能够在需要时填充它。显然,我遇到了问题,并且会看看是否有人可以看看我到目前为止所拥有的内容。
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class ViewLog 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 root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
File dir = new File (root.getAbsolutePath() + "/logs");
dir.mkdirs();
File file = new File(dir,"log.txt");
try {
FileOutputStream f = new FileOutputStream(file,true); //True = Append to file, false = Overwrite
PrintWriter pw = new PrintWriter(f);
System.out.println(s);
pw.println(s);
pw.flush();
pw.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);
}
}
任何帮助将不胜感激。我已经使用 adb 来查找该文件,但该文件并未被创建。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:这有效 - 刚刚测试过。
确保您拥有:>也在你的清单中。
Edit: This works - Just tested it.
Make sure you have:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /
> in your manifest as well.