我对以下任务之一有疑问:从控制台读取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
请向我解释为什么我的解决方案与正确的解决方案相比是错误的。谢谢。
这里是解释。第一个程序制作一个缓冲区读取器,其来源是键盘输入。然后,程序逐行读取并将结果保存在适当的字符串中。然后,程序生成用于读写文件的流(所谓的文件流)。之后,读取输入文件中的所有字节并将其放入缓冲区字节数组。第一我们需要检查文件中的字节数是偶数还是奇数,然后执行将字节复制到数组中的适当操作。复制缓冲区数组时要记住,范围在结尾处是排他的,在开始时是排他的,例如Arrays.copyOfRange(buffer,0,buffer.length / 2)在此间隔[0,buffer.length / 2>中复制字节。现在我们只需要在相应文件中写入字节。希望这会有所帮助。
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String inputFile = reader.readLine();
String outFile2 = reader.readLine();
String outFile3 = reader.readLine();
FileInputStream fileInputStream1 = new FileInputStream(inputFile);
FileOutputStream fileOutputStream2 = new FileOutputStream(outFile2);
FileOutputStream fileOutputStream3 = new FileOutputStream(outFile3);
byte[] buffer = Files.readAllBytes(Paths.get(inputFile));
byte[] bytesForOut2, bytesForOut3;
if(buffer.length % 2 == 0) {
bytesForOut2 = Arrays.copyOfRange(buffer, 0, buffer.length / 2);
bytesForOut3 = Arrays.copyOfRange(buffer, buffer.length /2, buffer.length);
}
else {
bytesForOut2 = Arrays.copyOfRange(buffer, 0, buffer.length / 2 + 1);
bytesForOut3 = Arrays.copyOfRange(buffer, buffer.length /2 + 1, buffer.length);
}
fileOutputStream2.write(bytesForOut2);
fileOutputStream3.write(bytesForOut3);
fileInputStream1.close();
fileOutputStream2.close();
fileOutputStream3.close();
}