【发布时间】:2020-05-05 12:19:50
【问题描述】:
我对其中一项任务有疑问: 从控制台读取 3 个文件名:file1、file2、file3。 分割文件: 将一半的内容保存到 file2 中,另一半保存到 file3 中。 如果字节数甚至没有将更多字节保存到file2中。 关闭流。
我想知道如何解决它,唯一有效的解决方案是:
public class main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String a = reader.readLine();
String b = reader.readLine();
String c = reader.readLine();
FileInputStream fileInputStream1 = new FileInputStream(a);
FileOutputStream fileOutputStream2 = new FileOutputStream(b);
FileOutputStream fileOutputStream3 = new FileOutputStream(c);
byte[] buffer = new byte[fileInputStream1.available()];
if (fileInputStream1.available() % 2 != 0) {
while (fileInputStream1.available() > 0) {
int count = fileInputStream1.read(buffer);
fileOutputStream2.write(buffer, 0, count / 2+1);
fileOutputStream3.write(buffer, count / 2+1, count/2);
}
} else {
while (fileInputStream1.available() > 0) {
int count = fileInputStream1.read(buffer);
fileOutputStream2.write(buffer, 0, count / 2);
fileOutputStream3.write(buffer, count / 2, count/2);
}
}
fileInputStream1.close();
fileOutputStream2.close();
fileOutputStream3.close();
}
}
我的问题是:为什么我必须从 count/2 保存到 count/2?这对我来说没有任何意义。如果我要使用数字,我们假设 file1 有 100 个字节。我从 0 保存到 count/2(100/2=50),从 count/2 保存到 count/2(从 100/2=50 到 100/2=50 甚至 50/2=25)。 在我看来,它应该是从 0 到 count/2 和从 count/2 到 count 或 buffer.length
请解释为什么我的解决方案与正确的解决方案相比是错误的。 谢谢。
【问题讨论】:
-
看
OutputStream.write的文档。第三个参数是要写入的数组部分的length,而不是位置。此外,您的解决方案不正确,因为available()没有给您文件中的字节数,只有在下一次读取操作中可读取的字节数。这也只是一个估计。阅读文档非常重要。 -
太棒了,这帮助了我。我会记得经常检查文档!
标签: java file fileinputstream fileoutputstream