简体   繁体   English

"Java Spring - 写入资源文件夹中的现有文件"

[英]Java Spring - write to existing file in resource folder

I have a simple in-memory db in which I load users from XML file at app startup.我有一个简单的内存数据库,我在应用程序启动时从 XML 文件加载用户。 Now whenever someone registers I want to save that new user in this xml file.现在,每当有人注册时,我都想将该新用户保存在此 xml 文件中。 My approach is to everytime get all the users, append new one and save to xml.我的方法是每次获取所有用户,追加新用户并保存到 xml。 However, seems like nothing is written in file at time the new user registers.但是,新用户注册时似乎没有任何内容写入文件。 I am aware that this approach is not save but this is for educational reason only.我知道这种方法不能保存,但这仅出于教育原因。

This is my save to xml class这是我保存到 xml 类

public class SaveXml {
    @Autowired
    private UserRepository userRepository;

    public void saveUserToXml (User newUser) {
        try {
            ClassLoader classLoader = getClass().getClassLoader();
            File file = new File(classLoader.getResource("Users.xml").getFile());
            FileWriter fileWriter = new FileWriter(file);

            List<User> usersList = new ArrayList<>();
            //populate arraylist with all users;
            userRepository.findAll().forEach(usersList::add);
            usersList.add(newUser);

            XmlMapper xmlMapper = new XmlMapper();
            String xmlContent = xmlMapper.writeValueAsString(usersList);
            fileWriter.close();
        }
        catch (Exception e){}
    }
}

Xml file that is placed in resource folder:放置在资源文件夹中的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user>
        <username>Tom</username>
        <password>123</password>
    </user>
    <user>
        <username>Moc</username>
        <password>1234</password>
    </user>
</users>

Users class用户类

@JacksonXmlRootElement(localName = "users")
@Data
@NoArgsConstructor
public class Users {
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<User> user;

    public Users(List<User> newUser) {
        this.user = newUser;
    }

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }
}

User class用户类

@Data
public class User
{
    @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
    //defining id as column name
    @Column
    private int id;
    //defining name as column name
    @Column
    private String username;
    //defining password column
    @Column
    private String password;
}

You could use FileUtils<\/code> from Apache.您可以使用 Apache 的FileUtils<\/code> 。

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
    </dependency>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM