【问题标题】:Printing to file using PrintWriter in Java not working with filename在 Java 中使用 PrintWriter 打印到文件不使用文件名
【发布时间】:2015-04-14 17:10:11
【问题描述】:

我正在创建一个程序来分析文本文件,我正在使用类来处理运行文件。我正在尝试将结果打印到文件中。我在同一个文件夹中创建了一个名为 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 class object printwriter


    【解决方案1】:

    如果它使用完整的文件路径而不是仅使用文件名,这可能是因为写入文件的当前目录不是您认为的那样。请参阅Getting the Current Working Directory in Java 以确定当前目录。

    【讨论】:

      【解决方案2】:
      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++;
      }
      

      把你的部分代码替换成上面的,这样应该可以找到类文件夹的report.txt文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-20
        • 2012-01-17
        相关资源
        最近更新 更多