Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 附加到文件&;从文件中读取,但什么也没发生_Java_File - Fatal编程技术网

Java 附加到文件&;从文件中读取,但什么也没发生

Java 附加到文件&;从文件中读取,但什么也没发生,java,file,Java,File,我正在尝试编写一个程序,在文件中创建一种数据库。它的基本函数是读取所有记录并将新记录附加到文件中,但每次尝试附加某些内容时,都不会发生任何事情 这是我的密码: 公共类存储文件{ FileWriter示例=新的FileWriter(“template.txt”,true); FileReader example2=新的FileReader(“template.txt”); BufferedWriter setNewRecord=新BufferedWriter(示例); BufferedReader

我正在尝试编写一个程序,在文件中创建一种数据库。它的基本函数是读取所有记录并将新记录附加到文件中,但每次尝试附加某些内容时,都不会发生任何事情

这是我的密码:

公共类存储文件{
FileWriter示例=新的FileWriter(“template.txt”,true);
FileReader example2=新的FileReader(“template.txt”);
BufferedWriter setNewRecord=新BufferedWriter(示例);
BufferedReader ReaderRecords=新的BufferedReader(示例2);
public SavingInFile()引发IOException{
}
void safeNewData(PersonRecord另一个PersonRecord)引发IOException{
setNewRecord=new BufferedWriter(示例);
setNewRecord.append(另一个personRecord.addNewRecord());
}
ArrayList getDataFromFile()引发IOException{
setNewRecord=new BufferedWriter(示例);
readTheRecords=新的BufferedReader(示例2);
ArrayList valuesKeeper=新的ArrayList();
System.out.println(readTheRecords.readLine());
while(readTheRecords.readLine()!=null){
if(readTheRecords.readLine()!=null){
String[]tempArray=readTheRecords.readLine().split(;);
PersonRecord tempRecord=新PersonRecord();
tempRecord.name=tempArray[0];
tempRecord.age=Integer.parseInt(tempArray[1]);
tempRecord.姓氏=tempArray[2];
tempRecord.salary=Integer.parseInt(tempArray[3]);
}
}
this.setNewRecord.close();
返回值keeper;
}
public void displayArrayList()引发IOException{
ArrayList示例=this.getDataFromFile();
迭代器iterateValues=example.Iterator();
while(iterateValues.hasNext()){
System.out.println(iterateValues.next().name+“”+iterateValues.next().name+“”+iterateValues.next().age+“”+iterateValues.next().salary+“”);
}
}
public void closeBuffers()引发IOException{
this.readTheRecords.close();
}
}
这是一个Person类,其中包含数据字段

public class PersonRecord {
    int age;
    double salary;
    String name;
    String surname;

    public PersonRecord() {
    }

    public PersonRecord(int age, double salary, String name, String surname) {
        this.age = age;
        this.salary = salary;
        this.name = name;
        this.surname = surname;
    }

    public int getAge() {
        return age;
    }

    public double getSalary() {
        return salary;
    }

    public String getName() {
        return name;
    }

    public String getSurname() {
        return surname;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    String addNewRecord() {
        return this.name+";"+this.surname+";"+String.valueOf(this.age)+";"+String.valueOf(this.salary);
    }
}
以下是我的主要观点:

公共类主{
公共静态void main(字符串[]args)引发IOException{
SavingInFile bufferToFile=新的SavingInFile();
ArrayList keeprocords=bufferToFile.getDataFromFile();
PersonRecord x=新的PersonRecord(10,13,“34”,“45”);
bufferToFile.saveNewData(x);
ArrayList示例=bufferToFile.getDataFromFile();
bufferToFile.displayArrayList();
closeBuffers();
}
}

有什么不对的建议吗?

首先,当您使用FileWrite和BufferWriter时,您必须确保将其关闭,或者使用try with resources,下面将解决您的问题: 我强烈建议以更干净的方式重写所有内容

void safeNewData(PersonRecord anotherPersonRecord) throws IOException {
    try (FileWriter example = new FileWriter("template.txt", true); BufferedWriter newRec = new BufferedWriter(example)){
        newRec.write(anotherPersonRecord.addNewRecord());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
你的代码有很多“异味”的地方。只需浏览以下资源:

  • 您在方法中隐藏了一些参数,使用后未正确关闭
  • 格式化代码非常有帮助(在像问题一样发布之前)
  • 有意义的命名变量有助于读取和维护代码
下面是重写的解决方案

记录类别:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class PersonRecord {
    String name;
    String surname;
    int age;
    double salary;

    String addNewRecord() {
        return String.format("%s;%s;%s;%s\n", this.name, this.surname, this.age, this.salary);
    }
}
将单独的实用程序类与个人文件一起用于处理操作:

final class PersonOperations {
    private Personoperations() {
    }

    public static void appendToFile(String fileName, List<PersonRecord> persons) throws IOException {
        @Cleanup
        BufferedWriter buffWriter = new BufferedWriter(new FileWriter(fileName, true));

        for (PersonRecord person : persons) {
            buffWriter.append(person.addNewRecord());
        }
    }

    public static List<PersonRecord> readFile(String fileName) throws IOException {
        @Cleanup
        BufferedReader buffReader = new BufferedReader(new FileReader(fileName));
        List<PersonRecord> persons = buffReader.lines()
                .filter(Objects::nonNull)
                .map(str -> {
                    String[] temp = str.split(";");
                    return PersonRecord.builder()
                            .name(temp[0])
                            .surname(temp[1])
                            .age(Integer.parseInt(temp[2]))
                            .salary(Double.parseDouble(temp[3]))
                            .build();
                })
                .collect(Collectors.toList());
        System.out.println("persons from file: " + persons);
        return persons;
    }

    public static void displayPersons(List<PersonRecord> persons) {
        for (PersonRecord person : persons) {
            System.out.println(person);
        }
    }
}
控制台输出:

persons from file: [PersonRecord(name=Garry, surname=Ford, age=45, salary=6000.0)]
PersonRecord(name=Garry, surname=Ford, age=45, salary=6000.0)
persons from file: [PersonRecord(name=Garry, surname=Ford, age=45, salary=6000.0), PersonRecord(name=Bob, surname=Dilan, age=34, salary=4500.0)]
PersonRecord(name=Garry, surname=Ford, age=45, salary=6000.0)
PersonRecord(name=Bob, surname=Dilan, age=34, salary=4500.0)
执行前的
template.txt
文件

Garry;Ford;45;6000  
Garry;Ford;45;6000 
Bob;Dilan;34;4500.0
执行后
template.txt

Garry;Ford;45;6000  
Garry;Ford;45;6000 
Bob;Dilan;34;4500.0
此外,我在那里使用了注释。您还可以保留本机getter和setter。并在读取后关闭资源(使用Autocloseable或finally块)

作为保存到
txt
文件的备选方案,您可以考虑:

  • 序列化:
  • 序列化到XML文件

我看到您在getDataFromFile()中有valuesKeeper,但不向其附加任何值。请检查下面的链接,它将帮助您: