[英]Printing to file using PrintWriter in Java not working with filename
我正在创建一个程序来分析文本文件,正在使用类对运行文件进行此操作。 我正在尝试将结果打印到文件中。 我已经在同一文件夹中创建了一个名为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);
}
}
如果它适用于完整的文件路径,但不能仅适用于文件名,则可能是因为您当前认为的不是文件所在的目录。 请参阅获取Java中的当前工作目录以确定当前目录。
Scanner sc = TextAnalyser.Linesc;
PrintWriter out = new PrintWriter(new FileWriter(
new File(LineCounter.class.getResource("Report.txt").toURI(), true));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
用上面的代码替换部分代码,这应该能够找到相对于class文件夹的report.txt
文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.