简体   繁体   English

如何使用Java从链接列表中的文本文件中读取字符串?

[英]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 我不记得如何从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 . 它使用Scanner类和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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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