Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a String[] to Arraylist<String> with java

I want to convert a string that I get from a file, to an arraylist. I tried it this way, but it doesn't work:

import java.io.*;
import java.util.*;

public class Data
{
    static File file = DataSaver.file;
    static List<String> data = new ArrayList<String>(512);
    public static void a() throws Exception
    {
        FileInputStream fis = new FileInputStream(file);
        DataInputStream dis = new DataInputStream(fis);
        BufferedReader reader = new BufferedReader(new InputStreamReader(dis));
        if(!file.exists())
        {
            throw new IOException("Datafile not found.");
        }
        else
        {
            String[] string = reader.readLine().split("$");
            for(int i = 0; i < string.length; i++)
            {
                data.add(string[i]);
            }
        }
        dis.close();
        System.out.println(data.toString()); //for debugging purposes.
    }
}

Ouput: [$testdata1$testdata2$]

Wanted output: [testdata1, testdata2]

File content: $testdata1$testdata2$

Can someone help me?

like image 891
Rheel Avatar asked Sep 28 '26 11:09

Rheel


1 Answers

String.split takes a regex and $ is a special char that need to be escaped. Also, the first char is a $ so splitting would end up with an empty first element (you need to remove it somehow, this is one way:

String[] string = reader.readLine().substring(1).split("\\$");

...or:

String[] string = reader.readLine().split("\\$");
for (int i = 0; i < string.length; i++)
    if (!string[i].isEmpty())
        data.add(string[i]);
like image 142
dacwe Avatar answered Oct 01 '26 00:10

dacwe