package addlinenumbers;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class AddLineNumbers {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int i=0;
try (FileOutputStream fos = new FileOutputStream ("dataInput.txt", true)) {
try (PrintWriter pw = new PrintWriter(fos)) {
String userInput = " ";
do {
System.out.print("Enter string to prepend to 'dataInput.txt'; -1 to EXIT: ");
userInput = input.nextLine();
if (!userInput.equals("-1")) {
pw.println(input.nextLine());
i++;
}
} while(!(userInput.equals("-1")));
}
} catch (FileNotFoundException fnfe) {
System.out.println("Unable to find dataInput.txt...");
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
} finally {
System.out.println("# of objects prepended: " + i);
System.out.println("Closing file...");
}
}
}
****************************OUTPUT**********************************************
run:
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
David
Goliath
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
Delilah
Samson
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
-1
# of objects prepended: 2
Closing file...
BUILD SUCCESSFUL (total time: 18 seconds)
正如你所看到的,它只包含了两个对象" Goliath"和"参孙"它们是写入文本文件的唯一字符串。从技术上讲,它应该有4个物体和#34; David"和#34; Delilah" 也应该在文本文件中,但它们不是。
非常感谢任何帮助。