0

我想替换文件中的字符并将内容复制到临时文件并将临时文件重命名为原始文件。

path = "/mnt/sdcard/TESTfile/"
File _f = new File(path);
File[] _f1 = _f.listFiles();
String[] s1 = { "t1.txt", "t2.txt", "t3.txt" };
_fOut = new FileOutputStream(path + File.separator + s1[i]);

// Copy the bits from input stream to output stream
StringBuffer sb = null;
BufferedWriter out = null;
while ((line = reader.readLine()) != null) {
    line = line.replaceAll("a"," ").replaceAll("g"," ");
    sb = new StringBuffer();
    Log.i("Line>>>" + line, "<<<<<");
    sb.append(line);

    s = sb.toString();
    byte[] temp = s.getBytes();
    _fOut.write(temp);
}
fis.close();
_fOut.close();

//old file name with path
String path1 = path + File.separator + s1[i];

 //new file name with path
String rename1 = path + File.separator + _f1[i].getName();
File oldFile = new File(path1);
File renameFile = new File(rename1);

for(int j = 0; j < _f1.length;j++)
{

oldFile.renameTo(renameFile);
}

这就是我试图做到的方式。我不确定如何重命名文件并删除原始文件。请帮忙

4

1 回答 1

0

要重命名文件,您需要 2 个File对象。使用原始路径创建一个,使用新名称创建第二个。然后调用original.renameTo(newFile)

删除文件更加容易。Android 上下文有一个名为deleteFile(name). 调用它来删除文件。请记住,该方法仅从本地存储文件夹中删除文件,并且不接受路径分隔符。如果您想从其他位置删除文件,file.delete()您也可以使用一种方法。

于 2012-11-13T16:18:13.203 回答