简体   繁体   中英

How do I set variable equal to the amount lines of strings that I have in my text doc for Java?

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;

}

}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM