0
我需要編寫一個程序,該程序將生成一個新文件,其中每行文本都有一個行號,給定一個沒有行號的輸入文件。例如:在輸入文本上書寫行號文件
定行: 「十六條」
輸出線: 「1 |十六條」,
行號的格式右對齊在3位,隨後|字符(在
之後有一個空格),然後是該行中的文本。
public class LineNumbers {
public static void process(File input, File output) {
Scanner scanner;
PrintWriter writer;
try {
scanner = new Scanner(input);
} catch (FileNotFoundException e) {
return;
}
try {
writer = new PrintWriter(output);
} catch (FileNotFoundException e) {
return;
}
for (int i = 1; scanner.hasNextLine(); i++) {
String s1 = scanner.nextLine();
String s2 = " " + i + " | " + s1;
writer.print(s2);
}
scanner.close();
writer.close();
}
}
這是代碼我有,這裏的字符串s2 ==輸出我需要的,但我如何過渡到一個輸出文件呢?
***** EDIT *****
這是需要的測試之一來運行,其中僅一條線被輸入的文件中。但是,在測試儀中,它只在行號前有兩個空格,當我更改我的代碼以匹配時,測試通過。所有其他測試者的寫法都是相似的,我認爲這可能會導致問題
@Test
public void testOneLine() {
try {
// create file
File input = folder.newFile("input.txt");
File output = folder.newFile("output.txt");
PrintWriter write = new PrintWriter(input);
write.println("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
write.close();
// invoke program
LineNumbers.process(input, output);
// verify file results
assertTrue ("Output file does not exist", output.exists());
Scanner scan = new Scanner(output);
String[] result = new String[] {
" 1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit."
};
for (String expected : result) {
if (scan.hasNext()) {
String actual = scan.nextLine();
assertEquals("Incorrect result", expected, actual);
}
else {
fail(String.format("Unexpected end of file: expected \"%s\"", expected));
break;
}
}
assertFalse ("File contains more data than expected", scan.hasNext());
scan.close();
}
catch (IOException e) {
fail("No exception should be thrown");
}
}
你已經在做它。問題是什麼 ? –
如果你能告訴問題是什麼,這將有所幫助,@Alex –
這是我的JUnit測試失敗,我不知道爲什麼。我認爲測試可能寫得不正確,但仔細看看它。有沒有辦法使用printf()寫輸出文件? –