简体   繁体   English

FileWriter在Arraylist中循环,但不写入文本文件

[英]FileWriter cycling through Arraylist but not writing to text file

I'm creating a log in form in Java and I've added a remember me method to store the log in data in a local text file for future us. 我正在用Java创建登录表单,并添加了一个“记住我”方法,用于将日志数据存储在本地文本文件中,以备将来使用。

The premise is that once the checkbox is checked, the email and password gets written out to the text file. 前提是选中此复选框后,电子邮件和密码就会写到文本文件中。

Here's the code below: 这是下面的代码:

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public void rememberMe() throws IOException {

private final ArrayList<String> storage = new ArrayList<String>();
protected String storPass;
protected String storEmail;


    storage.add(storEmail);
    storage.add(storPass);
    FileWriter writer = new FileWriter("local.txt"); 
    for(String i : storage) {
          writer.write(i);
          System.out.println("We have written " + i);
        }
      writer.close();
    }

with the output being: 输出为:

We have written EMAILADDRESS
We have written PASSWORD

The data has been removed, but the printing in the foreach look is showing me that it's cycling through the Arraylist correctly. 数据已删除,但是在foreach外观中的打印显示出它正在正确循环遍历Arraylist。

The local.txt doesn't have any data in it, it's empty before running and empty during and after the program is ran. local.txt中没有任何数据,它在运行前为空,在程序运行期间及之后为空。

Can anybody spot the problem I'm having? 有人可以发现我遇到的问题吗?

Thanks in advance. 提前致谢。

Instead of Using relative path use absolute path like D:\\\\local.txt . 代替使用相对路径,使用绝对路径,例如D:\\\\local.txt It will work 会工作的

Try using: 尝试使用:
Path locates/creates the file on the system 路径在系统上定位/创建文件
Then use the Files object to statically write the file using your list. 然后,使用Files对象使用列表静态写入文件。

Path file = Paths.get("local.txt");
Files.write(file, storage, Charset.forName("UTF-8"));

This way you can stay away from writing explicit foreach loop. 这样,您就可以避免编写显式的foreach循环。

here is more on the Files object which is available since java 1.7+ https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html 自Java 1.7+起https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html以来可用的文件对象更多信息

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

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