Question

Okay so I've got my class ( sorry about the formatting, not too familiar with the site )

import java.io.*;  
public class writingArray  
{  
    public static void writeToFile(String fileName, String[] input) {  
        PrintWriter printWriter;  
        try {    
            printWriter = new PrintWriter(new FileOutputStream(fileName, true));
            int length = input.length;    
            int i;  
            for(i = 0; ++i < length; i++) {  
                printWriter.println(input[i]);  
            }   
            printWriter.close();    
        }  
        catch(IOException e) {  
            System.out.println(e.getMessage());  
        }  
    }  
}

The problem is I want to write an array to a file with each entry being on a separate line and I want to wipe the file at the start from each write. Any advice on what to do? Because all I've managed to do is write the last entry of the array while wiping all the previous entries and yet I can write the last entry several times below itself.

Thanks ^^

Was it helpful?

Solution

for(i = 0; ++i < length; i++) {

I don't think you want to increase i twice. Get rid of the ++i.

OTHER TIPS

I strongly recommend using the library http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html which has already tackled many of these problems. If you transform your array to a List you can use:

public static void writeLines(File file,
                              Collection<?> lines)
                       throws IOException

Writes the toString() value of each item in a collection to the specified File line by line. The default VM encoding and the default line ending will be used.

The authors of the library have thought of many problems that most people don't such as line-endings, encodings, error trapping, etc. It's also likely to be as efficient as possible for general use.

for(i = 0; ++i < length; i++) { does look right, should this be for(i = 0; i < length; i++) { ?

Or, even better: for (String line : input) { }

Also, new FileOutputStream(fileName, true) will not clear the file, rather append to it.

import java.io.*;

public class writingArray {
    public static void writeToFile(String fileName, String[] input) {
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(new FileOutputStream(fileName));
            for (int i = 0; i < input.length; i++) {
                printWriter.println(input[i]);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top