Trying to read multiple lines from a one text file then print out results to new text file java

Solution 1:

You've told the scanner that tokens are separated by colons, and then you keep asking for 'what's after the next token'.

The problem is, you told scanner that all input is separated by a colon. So, not a newline then. The scanner dutifully reports that the 5th token in this file:

lastName:firstName:Test1:Test2:Test3
foobar:baz:1:2:3

would be: "Test3\nfoobar". After all, that sequence of characters in between the colons, isn't it? You see how two delimiters are involved here: A newline separates 2 records. Colons separate entries within a record. Scanner is not good at this job. So, don't use it.

Let's first get rid of the obsolete File API and use the new one, then, let's fix your resource leakage by using try-with-resources, which ensures that any resource you open you definitely close (that close() call you wrote? It won't be called if exceptions occur, for example). Let's also fix your deplorable error handling (don't ever catch an exception, do e.printStackTrace(), and keep on going. That's just nasty - you have no idea what just happened and yet the code will continue? When by definition the system is now in a state you haven't thought of? Not a good idea at all). And, of course, use the right tool for job, BufferedReader: It's a simpler API than scanner that just gets you lines. Which is what you want, and we'll deal with splitting the fields within a single record out on a line-by-line basis:

public static void main(String[] args) throws Exception {
  try (var in = Files.newBufferedReader(Paths.get("output.txt")) {
    processLine(in);
  }
}

static void processLine(String in) throws IOException {
  String[] parts = in.split(":");
  String lastName = parts[0];
  String firstName = parts[1];
  String test1 = Integer.parseInt(parts[2]);
  String test2 = Integer.parseInt(parts[3]);
  String test3 = Integer.parseInt(parts[4]);

  // rest of your code goes here
}