在Java中保存向量

时间:2015-03-13 16:58:44

标签: java

每次编辑时,如何将字符串向量保存到文件中?

所以,让我说我在向量中有用户名,在我添加或删除用户名后我希望保存该向量,所以如果程序关闭,它将显示最新的元素。

2 个答案:

答案 0 :(得分:2)

这应该可以帮助您入门。 正如JB Nizet所说,你应该使用ArrayList。 我还继续使用Java 7自动关闭功能,这可以确保您正确关闭文件句柄。

当然,您需要验证您的输入,并且您需要注意您坚持的内容。我怀疑你很快就会考虑更好的存储策略,但是,这会让你开始。

此外,由于它的作用类似于集合,因此您应该添加hashcode和equals。为了简洁起见,我没有添加它们。

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

public class PersistedCollection {
    private static final String NEWLINE_SEPARATOR = System.getProperty("line.separator");
    private final List<String> values;
    private final File file;

    public PersistedCollection(File file) {
        this.values = new ArrayList<>();
        this.file = file;
    }

    public void add(String value) {
        // You should validate this value. Remove carriage returns, make sure it meets your value specifications.
        values.add(value);
        persist();
    }

    public void remove(String value) {
        values.remove(value);
        persist();
    }

    private void persist() {
        // Using Java 7 autocloseable to ensure that the output stream is closed, even in exceptional circumstances.
        try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(this.file), 8192); Writer writer = new PrintWriter(outputStream)) {
            for (String value : values) {
                writer.append(value);
                writer.append(NEWLINE_SEPARATOR);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("PersistedCollection [values=");
        builder.append(values);
        builder.append(", file=");
        builder.append(file);
        builder.append("]");
        return builder.toString();
    }

    public static void main(String[] arguments) {
        PersistedCollection persistedCollection = new PersistedCollection(new File("/tmp/test.txt"));
        persistedCollection.add("jazeee");
        persistedCollection.add("temporary user");
        persistedCollection.add("user402442");
        persistedCollection.add("JB Nizet");
        persistedCollection.remove("temporary user");
        System.out.println(persistedCollection);
    }
}

答案 1 :(得分:0)

另一个解决方案是创建一个类,您可以在其中添加从用户名文件中读取所需的所有方法(每行一个用户名)。然后你可以从任何地方引用这个类(因为修饰符是公共的)并调用方法,以便你从该文件中添加或删除用户名。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.io.File;

public class Test {

private static BufferedWriter bw;
private static ArrayList<String> vector=new ArrayList<String>();
private static String everything;

//add an username
public static void add(String x){
    vector.add(x);
}
//remove an username
public static void remove(String x){
    vector.remove(x);
}

//update the file with the new vector of usernames
public static void updateToFile() throws IOException{
    File username = new File("/home/path/to/the/file");
    FileWriter fw = new FileWriter(username.getAbsoluteFile());
    bw= new BufferedWriter(fw); 
for (String x:vector){
    bw.write(x.toString());     
    bw.write("\n");
    }
bw.close();
}

//you call this method to initialise your vector of usernames
//this implies that you already have a file of usernames
//one username per line
public static void setUsername() throws IOException{
    vector=new ArrayList<String>();
    BufferedReader br = new BufferedReader(new FileReader("/home/path/to/the/file"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        everything = sb.toString();
    } finally {
        br.close();
    }
    String lines[] = everything.split("\\r?\\n");
    for (String x:lines){
        vector.add(x);
    }

}

//print your usernames in the console
public static void printUsers(){
    for (String User:vector){
        System.out.println(User);
    }
}
}

然后它变得如此简单:

import java.io.IOException;

public class MainTest {
 public static void main(String[] args) throws IOException{
     Test.setUsername();
     Test.printUsers();
     Test.add("username5");
     Test.remove("username2");
     System.out.println("// add username5; remove username2");
     Test.printUsers();
     System.out.println("// file has been updated with the new state");
     Test.updateToFile();
     System.out.println("// veryfing update");
     Test.setUsername();
     Test.printUsers();


 }
}

输出: (前4个用户就是我在文件中的内容)

    username1
    username2
    username3
    username4
    // add username5; remove username2
    username1
    username3
    username4
    username5
    // file has been updated with the new state
    // verifying update
    username1
    username3
    username4
    username5