Bianca Fuller
Bianca Fuller

Reputation: 39

How to read a file and split the text by each line?

I need to read a text file that looks something like this

8 7
~~~~~~~
~~~~~~~
B~~~~~~
~~~~~~~
~~~~B~~
~~~~B~~
~~~~~~B
~~~~~~~
~~~~~~~

My program is recreating a Battleship game. I need to accept the values 8 and 7 but only print from the second line down. I'm supposed to use string.split (i believe). I need to print only the lines with ~'s and B's. I have the code already for reading the file, I'm just unsure how to split the file by line breaks.

File file = new File(args[1]);
    try 
        {
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) 
            {
            String themap = sc.nextLine();          
            System.out.println(themap); 
            }
        sc.close();
        } 
    catch (Exception e) 
        {
        System.out.println("ERROR: File does not exist");
        }

Upvotes: 0

Views: 1107

Answers (2)

user1907906
user1907906

Reputation:

Use Java 8 Paths, Path, Files.readAllLines, and streams (the input is in /tmp/layout.txt):

package stackoverflow;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class StackOverflow {

    public static void main(String[] args) throws IOException {
        Path layout = Paths.get("/tmp", "layout.txt");
        List<String> lines = Files.readAllLines(layout);
        lines.remove(0); // Don't print the first line.
        lines.stream().forEach(System.out::println);
    }
}

If you can't use Java 8, use

for (String line : lines) {
    System.out.println(line);
}

instead of

lines.stream().forEach(System.out::println);

Upvotes: 0

chubbsondubs
chubbsondubs

Reputation: 38676

You already are reading it line by line using sc.nextLine(). It is going to read the file line by line. There's no need to use split to get each line. To prove that change your println statement to add something to each line you know is not in the file.

System.out.println( "Yaya " + themap );

If you see Yaya in front of each line when you run your program then you know you are reading it line by line, and themap points to one line out of the file at each pass of the loop.

After that then you just need to search within that line to find the B's and 8's and extract those into another data structure. There are lots of ways to do that, but check the String api for methods that can help with that.

Upvotes: 1

Related Questions