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()写输出文件? –