简体   繁体   中英

Read different variables from a file [java] and put them into a JList

I have some difficulties writing a code wich should be able to read heterogeneous features from a .txt file. This is a sample file:

size=1.523763e-13 Type= aBc, KCd, EIf

I need to find this features and then put them in a Jlist on netbeans.

To find the size variable I've thought to use the BufferedReader class, but I don't know what to do next!

Any help? My code by far:

public String findSize() {
    String spec = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader("sample.txt"));
        String line = reader.readLine();
        while(line!=null) {
            if (line.contains("size")) {
                for(int i = line.indexOf("size")+1, i = line.length(), i++)
                    spec +=...;

You can do it easily by splitting the string you read via BufferedReader or Scanner .

In the below example I have used Scanner and am reading the lines from System.in . You can replace it to read the lines from your source file.

Here is the code snippet:

public static void main (String[] args)
{
    Scanner in = new Scanner(System.in);
    List<String> typeString;
    while(in.hasNext()) {
        String[] str = in.nextLine().split("=");
        System.out.println("Size: " + str[1].split(" ")[0] + " Type: " + str[2]);
        typeString = new ArrayList<>(Arrays.asList(str[2].split(", ")));
    }
}

Please note that this is just for demonstration purpose. You can split the String and play with the sub-strings and store them anyway you want.

Input:

size=1.523763e-13 Type=aBc, KCd, EIf

Output:

Size: 1.523763e-13 Type: aBc, KCd, EIf

typeString --> {aBc, KCd, EIf}

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