gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:22:34 25 4
gpt4 key购买 nike

我试图弄清楚如何加载 .java 文档并将其放入文本文档中...

需要做什么:

Write a program that opens a Java source file, adds line numbers, and saves the result in a new file. Line numbers are numbers which indicate the different lines of a source file, they are useful when trying to draw someone's attention to a particular line (e.g., "there's a bug on line 4"). Your program should prompt the user to enter a filename, open it, and then save each line to an output fix with the line numbers prepended to the beginning of each line. Afterward, display the name of the output file. The name of the output file should based on the input file with the '.' replaced by a '_', and ".txt" added to the end. (Hint: if you are using a PrintWriter object called pw to save the text file, then the line "pw.printf("%03d", x);" will display an integer x padded to three digits with leading zeros.)

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

001 公共(public)类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();
}
}
}

最佳答案

您需要在阅读时打印并计算。您还需要区分输出文件和输入文件。而且,我更愿意使用 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();
}

关于java - 将 .java 文件转换为 .txt 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40076821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com