简体   繁体   中英

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.

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.

The local.txt doesn't have any data in it, it's empty before running and empty during and after the program is ran.

Can anybody spot the problem I'm having?

Thanks in advance.

Instead of Using relative path use absolute path like 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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