FileInputStream Fread = new FileInputStream("somefilename");
FileOutputStream Fwrite = null;
for (int i = 1; i <= 5; i++)
{
String fileName = "file" + i + ".txt";
Fwrite = new FileOutputStream(fileName);
int c;
while ((c = Fread.read()) != -1)
{
Fwrite.write((char) c);
}
Fwrite.close();
}
Fread.close();
以上代码仅写入一个文件。如何使一个文件的内容写入多个文件?
答案 0 :(得分:2)
FYI:请注意,您使用的read()
方法将返回byte
,而不是char
,因此调用write((char) c)
应该只是write(c)
。
要在复制文件时并行写入多个文件,请为目标文件创建一个输出流数组,然后迭代该数组以将数据写入所有文件。
为了获得更好的性能,您应该始终使用缓冲区来执行此操作。一次写入一个字节效果不佳。
public static void copyToMultipleFiles(String inFile, String... outFiles) throws IOException {
OutputStream[] outStreams = new OutputStream[outFiles.length];
try {
for (int i = 0; i < outFiles.length; i++)
outStreams[i] = new FileOutputStream(outFiles[i]);
try (InputStream inStream = new FileInputStream(inFile)) {
byte[] buf = new byte[16384];
for (int len; (len = inStream.read(buf)) > 0; )
for (OutputStream outStream : outStreams)
outStream.write(buf, 0, len);
}
} finally {
for (OutputStream outStream : outStreams)
if (outStream != null)
outStream.close();
}
}
答案 1 :(得分:0)
您将必须创建多个FileOutputStream
fwrite1
,fwrite2
,fwrite3
实例,每个要写入的文件创建一个实例,然后在阅读时,您只需写给所有人。这就是您实现的方式。
答案 2 :(得分:-1)
添加此行:
Fread.reset();
Fwrite.close();
之后的
并将第一行代码更改为此:
InputStream Fread = new BufferedInputStream(new FileInputStream("somefilename"));
Fread.mark(0);
答案 3 :(得分:-1)
FRead
流一次到达末尾,然后没有什么可以使它从头开始。
要解决此问题,您可以:
FRead.reset()
FRead
的值缓存到某个位置,然后从此源写入FWrite
FileOutputStream
的数组/集合,并在迭代过程中将每个字节写入所有字节推荐的解决方案当然是第一个。
您的代码中也存在一些问题: