在Android中编辑现有文件

时间:2013-04-27 02:38:20

标签: java android file file-io

我正在尝试通过以下方式编辑设备上的现有文件:首先选择使用选择器检索文件路径的文件,如“mnt / sdcard / file.png”。然后我将它传递给读者阅读现有文件,然后通过移动每个字符的Ascii来修改它。然后再次覆盖它以替换旧的。

我已经在PC文件上的桌面应用程序上测试了代码,它运行完美,但不能用作Android应用程序。它曾在我的设备上工作过一次,但没有再次工作

关于我的所作所为:

1)在Mainafest文件中添加外部源权限的写入 2)选择正确的文件并检索它的路径 3)读取文件内容为真

        File file = f;
        FileInputStream fin;
        fin = new FileInputStream(file);
        byte fileContent[] = new byte[(int)file.length()];
        fin.read(fileContent);

4)修改文件字节 5)在原始文件中回写(覆盖)

        FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
        fos.write(enc_msg);
        fos.write((byte)seed);
        fin.close();
        fos.close();

6)再次将文件设置为null 7)在onClickListner

中调用finish()

先谢谢

2 个答案:

答案 0 :(得分:1)

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));

但是,必须断开设备与USB的连接。否则,您需要拔下并重新插入设备以查看更改。

答案 1 :(得分:0)

经过大量工作后,我已通过以下方式达成最终解决方案:

1)使用Common-io库 http://commons.apache.org/proper/commons-io/download_io.cgi

2)仅在导入common-io

之后编写此简单行
  FileUtils.writeByteArrayToFile(new File(file.getAbsolutePath()), myByteArray, false);

覆盖文件的最后一个属性(Fasle)..追加标记