开发者

Writing to file with Java

I am trying to write a simple method to save my document to a file (overwriting any previous contents of the file.) Unfortunately, my implementation does not seem to work. I am calling it on my document, which is, for all intents and purposes, an array of String. What I'd like to do is to write the contents of my array, with a separate line for each value in the array, the value in position [0] on the first line, and the value for [1] on the second. How would I go about this ?

This is my implementation so far :

  public void save()
   { 
      try
      {
         PrintWriter outputFile = 
            new PrintWriter(new BufferedWriter(new FileWriter(docName)));
         int lineNo = 1;

         while (lineNo != lineNo) // CHANGE THIS!!!
         {  outputFile.println(" ~ ");
            lineNo++;
         }
         outputFile.flush();
      }
      catch (Exception e)
      {
         System.out.println("Document: Touble writin开发者_JAVA百科g to "+docName);
         System.exit(1);
      }

}


If a is an array of strings,

for (String s : a)
     outputFile.println(s);

will print the array line-by-line to outputFile.


Iterator over the array, and write the current element.

    String document[] = {"String1","String2","String3"};
    PrintWriter outputFile = 
        new PrintWriter(new BufferedWriter(new FileWriter(docName)));
     int lineNo = 1;

     for(int i = 0; i < document.length; i++)
     {  outputFile.println(document[i]);
        lineNo++;
     }


// myDoc is the "array of string"
foreach (String line : myDoc) {
    outputFile.println(line);
}


I might write it more like this:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

/**
 * FileDemo
 * @author Michael
 * @since 2/26/11
 */
public class FileDemo
{
    public static void main(String[] args)
    {
        try
        {
            FileDemo fd = new FileDemo();
            fd.save("out/test.txt", args);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

    }

    public void save(String filePath, String [] lines) throws FileNotFoundException
    {
        PrintStream ps = null;

        try
        {
            ps = new PrintStream(new FileOutputStream(filePath));
            int lineNum = 1;
            for (String line : lines)
            {
                ps.printf("%5d %s\n", lineNum++, line);
            }
        }
        finally
        {
            close(ps);
        }
    }

    public static void close(PrintStream ps)
    {
        if (ps != null)
        {
            ps.flush();
            ps.close();
        }
    }
}

I didn't see any actual content in your code, so I added some. I didn't how a file with line numbers was very interesting. You'd be able to modify this to make it differently if you wish.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜