Shashwat Shashwat - 4 months ago 8
Java Question

Taking Input From a File using Java

I am making a chat program and till now I have written code which allows users to chat with other users.

Now, I save this chat In a

File(txt)
, and the next time the program starts, I take input from it and display it in the chat Box.

Here is the screen shot of the file

enter image description here

But When I take input, and set it into the MessageBox, this comes up:



Here is the code:

public void readFiles() {
while (x.hasNext()) {
users[i] = x.next();
i++;
}
}


Edit: Let me explain what I need. If I add a new line, then all the words would be on a new line, but I want the next sentence to be on the new line.

Answer

I assume you are using Scanner. Scanner will, by default, use any whitespace as a delimiter. This means it regards ordinary spaces (" ") the same as end of line characters ("\n").

What you can do instead is use the hasNextLine() and nextLine() methods. This will use end of line characters as delimiters.

Scanner scan = new Scanner(new File("file.txt"));
String line;
while (scan.hasNextLine()) {
    line = scan.nextLine();
}
Comments