【发布时间】: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...) 并没有奏效。