我正在创建一个程序来分析文本文件,我正在使用类来对运行文件执行此操作。我正在尝试将结果打印到文件中。我在同一文件夹中创建了一个名为 report.txt 的文件,但该文件中没有打印任何内容。我已经使用完整文件路径完成了此操作,并且工作正常,但是我想仅使用文件名来完成此操作,而不是提供它位于同一文件夹中。
任何关于如何将结果打印到文件report.txt的帮助将不胜感激
我的代码如下:
运行文件:
package cw;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.IOException;
public class TextAnalyser {
//Declaration of all Scanners to be used in other classes.
public static Scanner reader;
public static Scanner Linesc;
public static void main(String[] args) throws IOException {
//User enters a file to be scanned.
Scanner in = new Scanner(System.in);
System.out.println("Enter a filename");
String filename = in.nextLine();
File InputFile = new File(filename);
//Assign all scanners to scan users file.
Linesc = new Scanner(InputFile);
LineCounter Lineobject = new LineCounter();
Lineobject.TotalLines();
}
}
类文件
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.IOException;
public class LineCounter {
public static void TotalLines() throws IOException {
Scanner sc = TextAnalyser.Linesc;
PrintWriter out = new PrintWriter(new FileWriter("Report.txt", true));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
out.println("The total number of lines in the file = " + linetotal);
out.flush();
out.close();
System.out.println("The total number of lines in the file = " + linetotal);
}
}
最佳答案
如果它适用于完整文件路径,而不仅仅适用于文件名,则可能是因为写入文件的当前目录不是您想象的那样。请参阅Getting the Current Working Directory in Java确定当前目录。
关于java - 在 Java 中使用 PrintWriter 打印到文件无法使用文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29633426/