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.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));
            throw new IOException("Datafile not found.");
            String[] string = reader.readLine().split("$");
            for(int i = 0; i < string.length; i++)
        System.out.println(data.toString()); //for debugging purposes.

Ouput: [$testdata1$testdata2$]

Wanted output: [testdata1, testdata2]

File content: $testdata1$testdata2$

Can someone help me?


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("\\$");


String[] string = reader.readLine().split("\\$");
for (int i = 0; i < string.length; i++)
    if (!string[i].isEmpty())

1. Use ("\\$") to remove the special meaning of "$".

2. Use Arrays.asList() for the Conversion of Array TO ArrayList

From Java Docs :

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

This method also provides a convenient way to create a fixed-size list initialized to contain several elements:


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

ArrayList<String> arr = new ArrayList<String>(Arrays.asList(string));

You need to escape special characters with \\.

Change your split statement like below

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

Adding to @dacwe

String[] string = reader.readLine().substring(1).split("\\$");
List<String> data =Arrays.asList(string);

Need Your Help

SingleProducerConstrained and MaxDegreeOfParallelism

c# multithreading task-parallel-library tpl-dataflow

In the C# TPL Dataflow library, SingleProducerConstrained is an optimisation option for ActionBlocks you can use when only a single thread is feeding the action block:

Get Total of a column from Dataset in Time Format(HH:MM) using C# without using Linq


Is there a way to get the total of a column from a dataset without using a LINQ Query?