【问题标题】:How to increase file size when overwriting覆盖时如何增加文件大小
【发布时间】:2014-08-21 16:58:18
【问题描述】:

在覆盖文本文件时,有什么方法可以增加文本文件的大小以适应其内容?当我覆盖文件时,大小始终与原始大小相同。当我需要用比原来包含的更多字节覆盖它时,这是一个问题:

String actual_name = "/storage/sdcard0/my_file_name.xml";  
FileOutputStream fileos  = new FileOutputStream(actual_name);

/**do a bunch of stuff to create XML string**/

fileos.write(myXMLstring.getBytes());
fileos.close();

在我的例子中,原始文件大小是 1016 字节。即使我有 4k 字节的新数据,前 1016 个字节也全部写入文件。顺便说一句,我尝试删除该文件(如果存在)然后写入它,但这没有帮助:

String fname = "my_file_name.xml";         
File ROOT = Environment.getExternalStorageDirectory();
File file1 = new File(ROOT, fname);
if(!file1.exists()){
    file1.createNewFile();
}
else{
    //returns true but doesn`t change the file size or even the created date
    boolean did_delete = file1.delete();
    if (did_delete){
        file1.createNewFile();
    }
}
String x = file1.getAbsolutePath();
FileOutputStream fileos  = new FileOutputStream(x);

有什么建议吗?

【问题讨论】:

  • 第二次写入时前 1016 个字节的内容是否改变?不需要先删除现有文件。删除成功吗?检查 write() 的返回值。
  • 是的,文件内容确实发生了变化。删除返回真。 write() 有一个 void 返回,所以没有什么要检查的,但文件被正确写入新数据的前 1016 个字节。其他所有内容都被截断,因为文件大小没有改变。
  • 我也有同样的问题。我什至尝试先删除文件,然后 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE...) 并没有奏效。

标签: java android


【解决方案1】:

好的,这是我发现的:

删除:

myFile= new File(Environment.getExternalStorageDirectory(), filename);
myFile.delete();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myFile)));

myFile 指向您的文件的位置。

要真正看到文件名的大小发生了变化,您必须断开 USB 数据线,然后重新连接。我不确定这是 android 问题还是 Windows 问题(将文件缓存在内存中)。

【讨论】:

  • 很高兴知道。我相信我最初只是通过使用新文件名来解决这个问题。
猜你喜欢
  • 2017-05-27
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
相关资源
最近更新 更多