[英]convert a String[] to Arraylist<String> with java
I want to convert a string that I get from a file, to an arraylist. 我想将从文件中获取的字符串转换为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$]
输出:
[$testdata1$testdata2$]
Wanted output: [testdata1, testdata2]
想要的输出:
[testdata1, testdata2]
File content: $testdata1$testdata2$
文件内容:
$testdata1$testdata2$
Can someone help me? 有人能帮我吗?
String.split
takes a regex and $
is a special char that need to be escaped. String.split
需要一个正则表达式,而$
是需要转义的特殊字符。 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]);
1. Use ("\\\\$")
to remove the special meaning of "$"
. 1.使用
("\\\\$")
删除"$"
的特殊含义。
2. Use Arrays.asList()
for the Conversion of Array
TO ArrayList
2.使用
Arrays.asList()
将Array
转换为 ArrayList
From Java Docs : 从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().
(更改为返回列表,将其“写入”到数组。)与Collection.toArray()结合使用,此方法充当基于数组的API和基于集合的API之间的桥梁。 The returned list is serializable and implements RandomAccess.
返回的列表是可序列化的,并实现RandomAccess。
This method also provides a convenient way to create a fixed-size list initialized to contain several elements: 此方法还提供了一种方便的方法来创建固定大小的列表,该列表初始化为包含多个元素:
eg: 例如:
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 如下更改您的split语句
String[] string = reader.readLine().split("\\$");
Adding to @dacwe 添加到@dacwe
String[] string = reader.readLine().substring(1).split("\\$");
List<String> data =Arrays.asList(string);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.