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?
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With