我有一个包含5行的文本文件,我希望在这些行中读取并能够将它们编号为1 - 5,并将它们保存在不同的文件中。数字在行开始之前开始。我试图在循环中硬编码来读取数字,但我一直在收到错误。
public class TemplateLab5Bronze {
static final String INPUT_FILE = "testLab5Bronze.txt";
static final String OUTPUT_FILE = "outputLab5Bronze.txt";
public static void main(String[] args) {
try {
FileReader in = new FileReader(INPUT_FILE);
PrintWriter out = new PrintWriter(OUTPUT_FILE);
System.out.println("Working");
BufferedReader inFile = new BufferedReader(in);
PrintWriter outFile = new PrintWriter(out);
outFile.print("Does this print?\n");
String trial = "Tatot";
outFile.println(trial);
System.out.format("%d. This is the top line\n", (int) 1.);
System.out.format("%d. \n", (int) 2.);
System.out.format("%d. The previous one is blank.\n", (int) 3.);
System.out.format("%d. Short one\n", (int) 4.);
System.out.format("%d. This is the last one.\n", (int) 5.);
/*if(int j = 1; j < 6; j++){
outFile.print( i + trial);
}*/
String line;
do {
line = inFile.readLine();
if (line != null) {
}
} while (line != null);
inFile.close();
in.close();
outFile.close();
} catch (IOException e) {
System.out.println("Doesnt Work");
}
System.out.print("Done stuff!");
}
}
这是我到目前为止的所有代码,不包括import语句,评论的for循环是我试图使用的。还有另一种方法吗?
答案 0 :(得分:0)
您不需要两个PrintWriter
。只使用一个。
PrintWriter outFile = new PrintWriter(OUTPUT_FILE);
您可以简单地使用计数器而不是for
循环(您错误地将其写为if
- 正如@Shirkam所提到的那样)
String line;
int count=1;
do {
line = inFile.readLine();
if (line != null) {
outFile.println( count++ +"." + line);
}
} while (line != null);
inFile.close();
这在我的最后工作正常。
答案 1 :(得分:0)
执行此操作的一种方法是在循环浏览现有文件时添加到printWriter
:
FileReader fr = new FileReader("//your//path//to//lines.txt");
BufferedReader br = new BufferedReader(fr);
try (PrintWriter writer = new PrintWriter("//your//other//path//newlines.txt", "UTF-8")) {
String line;
int num = 1;
while ((line = br.readLine()) != null) {
writer.println(num + ". " + line);
num++;
}
}
注意:我没有输入任何catch
语句,但您可能希望捕获以下部分/全部内容:FileNotFoundException
,UnsupportedEncodingException
,{{1} }