James Gould
James Gould

Reputation: 4702

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.

Upvotes: 0

Views: 226

Answers (2)

ephemeralCoder
ephemeralCoder

Reputation: 307

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

Upvotes: 0

Rahman
Rahman

Reputation: 3785

Instead of Using relative path use absolute path like D:\\local.txt. It will work

Upvotes: 1

Related Questions