使用Java将String[]转换为ArrayList<String>

3

我想将从文件中获取的字符串转换成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 $

有人能帮我吗?


你为什么把一个 String 数组叫做 'string'? - David B
为什么不行?你对“字符串”这个词有问题吗? - Rheel
这是一个糟糕的变量名。Java 可能允许它,因为它的类不区分大小写,但在 C# 中就行不通了(其中 stringString 的别名)。此外,它并没有真正描述变量中包含的内容。 - David B
如果你想读取文本,请不要使用DataInputStream,它更令人困惑而不是有用。 - Peter Lawrey
4个回答

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]);

没问题 @user1546467,很高兴能够帮助! :) - dacwe

3

1. 使用("\\$")来去除"$"的特殊含义。

2. 使用Arrays.asList()Array转换为ArrayList

根据Java文档:

返回由指定数组支持的固定大小列表。(对返回的列表进行的更改“写入”到数组中)。此方法充当基于数组和基于集合的API之间的桥梁,与Collection.toArray()结合使用。返回的列表是可序列化的并实现了RandomAccess。

该方法还提供了一种方便的方法来创建初始化为包含多个元素的固定大小列表:

例如:

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

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

@dacwe Arrays.asList()返回的List直接由数组支持,这意味着几乎没有开销。 - Stefan

1

您需要使用\\转义特殊字符。

将您的分割语句更改如下:

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

0

补充@dacwe所说的内容

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

如果您想为他的回答做出贡献,请编辑它或留下评论。 - David B
好的,但是@user1546467想要一个ArrayList(asList返回由数组支持的列表)。 - dacwe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接