在我的程序中,我尝试将输出打印到文件但文件为空。该程序读取目录中的文本文件。我得到了所需的输出到控制台,但没有在output.text文件中。不确定程序中缺少什么。提前感谢您的帮助。
import java.io.*;
public class CacheData {
public static void main(String[] args) throws IOException {
String target_dir = "C:\\Files";
String output = "C:\\Files\\output.txt";
File dir = new File(target_dir);
File[] files = dir.listFiles();
for (File textfiles : files) {
if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(textfiles));
String line;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
PrintWriter outputStream = new PrintWriter(output);
outputStream.println();
outputStream.close();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
}
答案 0 :(得分:0)
PrintWriter outputStream = new PrintWriter(output);
//you are not printing anything to output file.
outputStream.println();
//Change it to
outputStream.println(line);
outputStream.close();
答案 1 :(得分:0)
对您的代码进行一些修改以写入您的文件。请参阅内联注释以获取更多信息。
import java.io.*;
public class CacheData {
public static void main(String[] args) throws IOException {
String target_dir = "C:\\Files";
String output = "C:\\Files\\output.txt";
File dir = new File(target_dir);
File[] files = dir.listFiles();
for (File textfiles : files) {
if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(textfiles));
String line;
//open the Printwriter before your loop
PrintWriter outputStream = new PrintWriter(output);
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
//Write Content not just linebreaks
outputStream.println(line);
}
//close the outputstream after the loop
outputStream.close();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
}
要在文件中写入每个txt-File的内容,请在for循环之前移动Printwriter,然后在for循环之后关闭printwriter,而不仅仅是while循环。
答案 2 :(得分:0)
您希望将多个文件(在您的案例中为文本文件)的内容合并到一个文件中。
这是一个更简单的IMO解决方案。更简单的是,您不必担心在读或写时自己打开和关闭文件。
public static void main(String[] args) throws Exception {
String targetDir = "Path to your directory of input files";
String outputFile = "Path to your output file";
File dir = new File(targetDir);
File[] files = dir.listFiles(new FilenameFilter() {
// Only get files that end with .txt
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
// Read all file lines into a List
List<String> inputFileLines = new ArrayList<>();
for (File file : files) {
inputFileLines.addAll(Files.readAllLines(Paths.get(file.getAbsolutePath())));
}
// Write the List to the console
for (String line : inputFileLines) {
System.out.println(line);
}
// Write the List to a single file
Files.write(Paths.get(outputFile), inputFileLines, StandardOpenOption.CREATE);
}