0

I am putting together strings such as:

spagetti

Spinich

cheese

etc down the list in a text doc, how can I assign each a specified variable that I can call from in eclipse ?

like calling spagetti as “1” or “1a”

I am new at java and would like to know

All I have right now is

{

import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;

public class FileAccess {

    private static String fileName = "ingredients";

    private static Scanner inputStream = null;

}

}
Arbauman
  • 30
  • 7
j doe
  • 1
  • 2

1 Answers1

0

You can try something like this

Path filePath = Paths.get("path/to/your/file");
String[] lines = Files.newBufferedReader(filePath)
                      .lines()
                      // discard lines that only contain whitespaces
                      .filter(line -> !line.matches("^\\s+$")
                      .toArray(String[]::new);

So now you can access the first line as lines[0], second line as lines[1], etc.

Or traverse the array

for (int i = 0; i < lines.length; i++)
    System.out.println(lines[i]);

Or use for-each loop

for (String line: lines)
    System.out.println(line);
Meme Composer
  • 5,895
  • 4
  • 18
  • 33