开发者

Writing an array to a file

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 ^^


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

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


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();
            }
        }
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜