将.java文件转换为.txt文档

时间:2016-10-17 00:03:16

标签: java text

我试图找出如何加载.java文档并将其放入文本文档...

需要做什么:

  

编写一个打开Java源文件,添加行号和的程序   将结果保存在新文件中。行号是数字   表示源文件的不同行,它们在何时有用   试图引起别人对特定线路的注意(例如,   "第4行和第34行有一个错误。您的程序应该提示用户   输入文件名,打开它,然后将每一行保存到输出修复程序   行号前面加上每行的开头。   然后,显示输出文件的名称。输出的名称   文件应该基于输入文件与'。'取而代之的是' _',   和" .txt"添加到最后。 (提示:如果您使用的是PrintWriter   对象叫pw保存文本文件,然后是行   " pw.printf("%03d",x);"将显示一个整数x填充为三   带前导零的数字。)

text.java需要输出带有编号行的文本文档,例如:

001公共类dogHouse {

002 public static void main(String [] args){

<00>等等......

004

import java.io.*;

    public class dogHouse {
        public static void main(String [] args) throws IOException {

            // The name of the file to open.
            String fileName = "test.java";

            // This will reference one line at a time
            String line = null;

            try {
                // FileReader reads text files in the default encoding.
                FileReader fileReader = 
                    new FileReader(fileName);

                // Always wrap FileReader in BufferedReader.
                BufferedReader bufferedReader = 
                    new BufferedReader(fileReader);

                while((line = bufferedReader.readLine()) != null) {
                    System.out.println(line);
                }   

                // Always close files.
                bufferedReader.close();         
            }

            // The name of the file to open.
            finally {
                // Assume default encoding.
                FileWriter fileWriter =
                    new FileWriter(fileName);

                // Always wrap FileWriter in BufferedWriter.
                BufferedWriter bufferedWriter =
                    new BufferedWriter(fileWriter);

                // Note that write() does not automatically
                // append a newline character.
                bufferedWriter.write("Hello there,");
                // Always close files.
                bufferedWriter.close();
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您需要在阅读时打印并计算line(s)。您还需要区分输出文件和输入文件。而且,我更愿意使用try-with-resources Statements。像,

String fileName = "test.java";
String outputFileName = String.format("%s.txt", fileName.replace('.', '_'));
try (BufferedReader br = new BufferedReader(new FileReader(fileName));
        PrintWriter pw = new PrintWriter(new FileWriter(outputFileName))) {
    int count = 1;
    String line;
    while ((line = br.readLine()) != null) {
        pw.printf("%03d %s%n", count, line);
        count++;
    }
} catch (Exception e) {
    e.printStackTrace();
}