簡體   English   中英

將.java文件轉換為.txt文檔

[英]Converting a .java file to a .txt document

我試圖弄清楚如何加載.java文檔並將其放入文本文檔中...

需要做什么:

編寫一個程序來打開Java源文件,添加行號,並將結果保存到新文件中。 行號是表示源文件不同行的數字,當試圖引起某人對特定行的注意時,它們很有用(例如,“第4行有錯誤”)。 您的程序應提示用戶輸入文件名,將其打開,然后將每行保存到輸出修訂中,並在每行的開頭加上行號。 然后,顯示輸出文件的名稱。 輸出文件的名稱應基於帶有“。”的輸入文件。 替換為“ _”,並在末尾添加“ .txt”。 (提示:如果您使用名為pw的PrintWriter對象保存文本文件,則“ pw.printf(“%03d”,x);”行將顯示一個整數x,該整數x會填充到以零開頭的三位數字。)

text.java需要使用編號的行輸出到文本文檔中,例如:

001公共類dogHouse {

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

003等...

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();
            }
        }
    }

閱讀時,您需要打印並計算line數。 您還需要區分輸出文件和輸入文件。 而且,我更喜歡使用try-with-resources語句 就像是,

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM