我有许多.txt
文件,我想把它们连接起来生成一个文本文件。
我该如何在Java中实现?
以下是解答:
file1.txt file2.txt
连接的结果为
file3.txt
使得 file1.txt
的内容被 file2.txt
的内容所跟随。
我有许多.txt
文件,我想把它们连接起来生成一个文本文件。
我该如何在Java中实现?
file1.txt file2.txt
连接的结果为
file3.txt
使得 file1.txt
的内容被 file2.txt
的内容所跟随。
你可以使用Apache Commons IO库。该库包含了FileUtils
类,详见这里。
// Files to read
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
// File to write
File file3 = new File("file3.txt");
// Read the file as string
String file1Str = FileUtils.readFileToString(file1);
String file2Str = FileUtils.readFileToString(file2);
// Write the file
FileUtils.write(file3, file1Str);
FileUtils.write(file3, file2Str, true); // true for append
此类中还有其他方法可以更优化地完成任务(例如使用流或列表)。
如果您正在使用Java 7+,
public static void main(String[] args) throws Exception {
// Input files
List<Path> inputs = Arrays.asList(
Paths.get("file1.txt"),
Paths.get("file2.txt")
);
// Output file
Path output = Paths.get("file3.txt");
// Charset for read and write
Charset charset = StandardCharsets.UTF_8;
// Join files (lines)
for (Path path : inputs) {
List<String> lines = Files.readAllLines(path, charset);
Files.write(output, lines, charset, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
}
}
逐个读取文件并将它们写入目标文件。可以尝试如下代码:
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[n];
for (String file : files) {
InputStream in = new FileInputStream(file);
int b = 0;
while ( (b = in.read(buf)) >= 0)
out.write(buf, 0, b);
in.close();
}
out.close();
对我来说这很好用。
// open file input stream to the first file file2.txt
InputStream in = new FileInputStream("file1.txt");
byte[] buffer = new byte[1 << 20]; // loads 1 MB of the file
// open file output stream to which files will be concatenated.
OutputStream os = new FileOutputStream(new File("file3.txt"), true);
int count;
// read entire file1.txt and write it to file3.txt
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
// open file input stream to the second file, file2.txt
in = new FileInputStream("file2.txt");
// read entire file2.txt and write it to file3.txt
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
os.close();
你的意思是需要一个文件包含其他文本文件的内容吗?那么,读取每个文件(可以在循环中完成),将它们的内容保存在StringBuffer/ArrayList中,并通过将这些保存的文本从StringBuffer/ArrayList刷新到最终的.txt文件来生成最终的.txt文件。
别担心,这是一项简单的任务。只要熟悉给定的系统,你就没问题了 :)
听起来像是作业...
如果你需要知道如何在Java中创建/打开/读取/写入/关闭文件,请搜索文档。那些信息应该是广泛可得的。