开发者

How to save the data into File in java?

I have one problem, that is I have one string of data and I want to save it into a separate fil开发者_StackOverflow中文版e every time. Please give me a suggestion.

Thanks, vara kumar.pjd


Use a timestamp in the filename so you can be sure it is unique. Below example uses a timestamp in milliseconds which should be enough in most cases.

If you expect you can have multiple files within 1 millisecond then you could do something with a GUID/UUID. Note that GUID/UUID could result in duplicates too, however this chance is extremely rare.

import java.io.*;
class FileWrite 
{
   public static void main(String args[])
  {
      try{
    // Create file 
    FileWriter fstream = new FileWriter(System.currentTimeMillis() + "out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
    out.write("Hello Java");
    //Close the output stream
    out.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}


You don't need to compute the filename by yourself, have a look at File.createTempFile.

From the javadoc:

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:

  1. The file denoted by the returned abstract pathname did not exist before this method was invoked, and
  2. Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.

This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.


A one liner. Using base 36 for the ids will make the file names shorter.

IOUtils.write(text, new FileWriter(Long.toString(System.currentTimeMillis(), 36)+".txt")));

http://commons.apache.org/io/


One solution can be, use a random number generator to generate a random number. Use this random number with some text as a filename. Maintain a list of already used names and each time you are saving the file, check through this list if the file name is unique.


One of possible ways to get File object with unique name could be:

public static File getUniqueFile(String base, String ext, int index) {
    File f = new File(String.format("%s-%03d.%s", base, index, ext));
    return f.exists() ? getUniqueFile(base, ext, index + 1) : f;
}

Update: and here goes basic usage/test case:

    String s = "foo string\n";

    FileWriter writer = null;

    for (int i = 0; i < 10; i++) {
        File f = getUniqueFile("out", "txt", 0);
        try {
            writer = new FileWriter(f);
            writer.write(s);
            writer.close();
            writer = null;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }

    if (writer != null) { try { writer.close(); } catch (Exception e) {} }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜