简体   繁体   中英

How do I read strings from a textfile in Linked List usings Java?

I don't remember how to get strings from a textfile.txt

I just have a two commands and then the name of the info

I = Insert
D = Delete

Example:

I Blue
I Red
D Blue
I Green
D Red
D Green

So one would be String command and the other String info

Any help??

EDIT:

I forgot to mention it tells me to prompt the user to specify the name of the input file

This is a little primitive but it works. It uses Scanner class and StringTokenizer . Of course, there could be many other ways to do it.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;

public class FReader {
    public static void main(String[] args) throws FileNotFoundException {
    System.out.println("Enter file name:");
    Scanner input = new Scanner(System.in);
    String fname = input.nextLine();
    File file = new File(fname);
    Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            StringTokenizer tokens = new StringTokenizer(line);
            String command = tokens.nextToken();
            String info = tokens.nextToken();
            System.out.println("command = " + command + " info = " + info);
        }
    }
}

EDIT: It was tested for the following data:

I Blue
I Red 
D Blue 
I Green
D Red 
D Green

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