[英]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.