从文件中读取字符串数组

时间:2015-11-28 17:05:20

标签: java arrays string read-write

我有这段代码:

public static void write() throws IOException{
    ObjectOutputStream out = new ObjectOutputStream(
            new FileOutputStream("ips.txt")
        );
    for ( int  i = 0; i < Main.ipList.length; i++){
        out.writeObject(ipList[i]);
    }
        out.flush();
        out.close();
}

将字符串数组写入文本文件:

static String[] ipList = {"127.0.0.1", "173.57.51.111"};

我想知道如何读取文本文件并使用新的ips编辑ipList。

2 个答案:

答案 0 :(得分:1)

如果您想将String个对象写入文件,最好使用FileWriter而不是ObjectOutputStream。同样,使用FileReader从文件中读取。有关如何使用这些Reader对象的信息,请参见https://docs.oracle.com/javase/tutorial/essential/io/charstreams.html

ObjectOutputStream通常适用于编写实现java.io.Serializable接口的更复杂对象。

以下是一个例子:

BufferedReader inputStream = null;
List<String> ipList = new ArrayList<>();
try {
    inputStream = new BufferedReader(new FileReader("ips.txt"));
    String l;
    while ((l = inputStream.readLine()) != null) {
       ipList.add(l);
    }
} finally {
    if (inputStream != null) {
        inputStream.close();
    }  
}

// get an array from the ArrayList
ipArray = ipList.toArray(new String[ipList.size()]);

答案 1 :(得分:-1)

您可以尝试这样的事情

package a;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class A {

    static String[] ipList = { "127.0.0.1", "173.57.51.111" };

    public static void main(String[] args) {

        try {
            write();
            update();
        } catch (IOException e) {
            System.err.println(e);
        }

        Arrays.asList(ipList).stream().forEach(System.out::println);
    }

    // Your method
    public static void write() throws IOException {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("ips.txt"));
        for (int i = 0; i < A.ipList.length; i++) {
            out.writeObject(ipList[i]);
        }
        out.flush();
        out.close();
    }

    public static void update() throws IOException {

        List<String> lines = Files.readAllLines(Paths.get(".", "newIps.txt"));

        List<String> newIps = new ArrayList<>();
        newIps.addAll(Arrays.asList(ipList));
        newIps.addAll(lines);
        ipList = newIps.toArray(ipList);
    }
}

newIps.txt文件的内容为

0.0.0.0
192.168.1.1

程序的输出是

127.0.0.1
173.57.51.111
0.0.0.0
192.168.1.1

请注意,Arrays.asList(ipList)会在数组上返回一个桥接列表(对列表的任何更改都将在数组中可见),因此我们执行putAll