我想在root上创建一个文件夹并放入txt文件并附加数据 '
我的java代码
public void generateNoteOnSD(String sFileName, String sBody){
try
{
String fileName = "error";
String headings = "Hello, world!";
String path = "/data/root/";
File file = new File(path, fileName+".txt");
if (!file.exists()) {
file.mkdirs();
}
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
// Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
Log.d("file error", ""+e.getMessage());
}
}
我收到文件未找到异常
请帮助我如何在内部存储中的根文件夹上创建文件
答案 0 :(得分:2)
尝试此功能。
public void wrtieFileOnInternalStorage(Context mcoContext,String sFileName, String sBody){
File file = new File(mcoContext.getFilesDir(),"mydir");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
}
}
答案 1 :(得分:1)
尝试这样的事情 -
public Boolean writeToSD(String text){
Boolean write_successful = false;
File root=null;
try {
// <span id="IL_AD8" class="IL_AD">check for</span> SDcard
root = Environment.getExternalStorageDirectory();
Log.i(TAG,"path.." +root.getAbsolutePath());
//check sdcard permission
if (root.canWrite()){
File fileDir = new File(root.getAbsolutePath());
fileDir.mkdirs();
File file= new File(fileDir, "samplefile.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write(text);
out.close();
write_successful = true;
}
} catch (IOException e) {
Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());
write_successful = false;
}
return write_successful;
}
答案 2 :(得分:0)
在此声明中:
File gpxfile = new File(file, sFileName);
文件应该是目录(这里使用.txt
文件)。
另外,请阅读this。您可以将文件存储在/data/data/<your.package.name>/
目录中(尝试使用/data/root/
会导致权限被拒绝错误)。
答案 3 :(得分:0)
试试这个。使用这个,我在SD卡中创建了日志文件。
public void writeFile(String text){
File tarjeta = Environment.getExternalStorageDirectory();
File logFile = new File(tarjeta.getAbsolutePath()+"/", "log.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}