所以我需要编写一个代码,使文本,pdf,jpg,...的大小直到 或等于1474560(软盘的大小)。问题是如何进行此限制,以便writeFile将停止直到1474560大小。
void newFileParser(String initialPath, String finalPath){
try{
FileWriter writeFile = new FileWriter(finalPath,true);
File newfile = new File(finalPath);
while(newfile.length() < 1474560){
writeFile.write("0\n");
}
writeFile.close();
if(newfile.length() <= 1474560){
System.out.println("New file is done");
}
System.out.println("The size of the NewFile: " + newfile.length());
}
catch (IOException e){
System.out.println("An error occurred");
e.printStackTrace();
}
}
答案 0 :(得分:2)
您使用FileWriter
来缓冲输出。这意味着newFile.length()
可能不返回您写入的字节数,而是当前刷新到磁盘的字节数。
只需使用具有特定迭代次数的循环即可。并请记住在finally
子句中关闭编写器,或使用try-with-resources
,如下所示:
void newFileParser(String initialPath, String finalPath) {
File newfile = new File(finalPath);
long initialLength = 0;
if (newfile.exists()) {
initialLength = newfile.length();
}
try (FileWriter writeFile = new FileWriter(finalPath, true)) {
for (int i = 0; i < 1474560 - initialLength; i++) {
writeFile.write(0);
}
}
catch (IOException e) {
System.out.println("An error occurred");
e.printStackTrace();
}
System.out.println("The size of the NewFile: " + newfile.length());
}