使用Java将内容从一个文件复制到多个文件

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();

上面的代码仅写入一个文件。如何使一个文件的内容写入多个文件?


慕尼黑的夜晚无繁华
浏览 363回答 3
3回答

扬帆大鱼

添加此行:Fread.reset();后&nbsp;Fwrite.close();并将第一行代码更改为此:InputStream&nbsp;Fread&nbsp;=&nbsp;new&nbsp;BufferedInputStream(new&nbsp;FileInputStream("somefilename")); Fread.mark(0);

MMMHUHU

仅供参考:请注意,read()您使用的方法返回abyte而不是a char,因此调用write((char) c)本来应该是just write(c)。要在复制文件时并行写入多个文件,请为目标文件创建一个输出流数组,然后迭代该数组以将数据写入所有这些文件。为了获得更好的性能,您应该始终使用缓冲区来执行此操作。一次写入一个字节效果不佳。public static void copyToMultipleFiles(String inFile, String... outFiles) throws IOException {&nbsp; &nbsp; OutputStream[] outStreams = new OutputStream[outFiles.length];&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < outFiles.length; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outStreams[i] = new FileOutputStream(outFiles[i]);&nbsp; &nbsp; &nbsp; &nbsp; try (InputStream inStream = new FileInputStream(inFile)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byte[] buf = new byte[16384];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int len; (len = inStream.read(buf)) > 0; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (OutputStream outStream : outStreams)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outStream.write(buf, 0, len);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; for (OutputStream outStream : outStreams)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (outStream != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outStream.close();&nbsp; &nbsp; }}

偶然的你

该FRead流取得到最后一次,再没有什么让它从头开始。要解决此问题,您可以:FRead.reset()每次写入文件后调用将FRead值缓存在某个位置并FWrite从此源写入创建一个数组/的集合,FileOutputStream并在迭代过程中将每个字节写入所有字节推荐的解决方案当然是第一个。您的代码中也存在一些问题:强烈建议您对流使用try-with-resouce,因为应安全关闭它们您似乎不遵循命名约定,即在lowerCamelCase中命名变量
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java