我想将从文件中获取的字符串转换为arraylist。我试过这种方式,但它不起作用:
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.
}
}
输出继电器:
[$testdata1$testdata2$]
通缉输出:
[testdata1, testdata2]
文件内容:
$testdata1$testdata2$
有人可以帮助我吗?
答案 0 :(得分:6)
String.split
使用正则表达式,$
是需要转义的特殊字符。此外,第一个字符是$
,因此拆分最终会得到一个空的第一个元素(你需要以某种方式删除它,这是一种方式:
String[] string = reader.readLine().substring(1).split("\\$");
...或:
String[] string = reader.readLine().split("\\$");
for (int i = 0; i < string.length; i++)
if (!string[i].isEmpty())
data.add(string[i]);
答案 1 :(得分:3)
1。使用("\\$")
删除"$"
的特殊含义。
2。使用Arrays.asList()
进行转换 Array
至ArrayList
来自Java Docs:
返回由指定数组支持的固定大小的列表。 (对返回列表的更改“直写”到数组。)此方法与Collection.toArray()结合,充当基于数组的API和基于集合的API之间的桥梁。返回的列表是可序列化的,并实现RandomAccess。
此方法还提供了一种方便的方法来创建初始化为包含多个元素的固定大小的列表:
<强>例如强>
String[] string = reader.readLine().split("\\$");
ArrayList<String> arr = new ArrayList<String>(Arrays.asList(string));
答案 2 :(得分:1)
您需要使用\\
转义特殊字符。
更改您的拆分声明,如下所示
String[] string = reader.readLine().split("\\$");
答案 3 :(得分:0)
添加到@dacwe
String[] string = reader.readLine().substring(1).split("\\$");
List<String> data =Arrays.asList(string);