java中如何将数据保存到文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4499562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 18:04:33  来源:igfitidea点击:

How to save the data into File in java?

javafile-ioio

提问by varakumar.pjd

I have one problem, that is I have one string of data and I want to save it into a separate file every time. Please give me a suggestion.

我有一个问题,那就是我有一个数据字符串,我想每次都将它保存到一个单独的文件中。请给我一个建议。

Thanks, vara kumar.pjd

谢谢,vara kumar.pjd

采纳答案by Mark Baijens

Use a timestamp in de filename so you can be sure it is unique.

在 de 文件名中使用时间戳,以确保它是唯一的。

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

This is something that is very easy to google.

这是很容易用谷歌搜索的东西。

回答by Mudassir

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.

一种解决方案是,使用随机数生成器生成随机数。将此随机数与一些文本一起用作文件名。维护已使用名称的列表,每次保存文件时,检查此列表是否文件名是唯一的。

回答by Peter Lawrey

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

一个班轮。使用基数 36 作为 ID 将使文件名更短。

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

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

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

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

回答by barti_ddu

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

获取具有唯一名称的File对象的一种可能方法是:

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) {} }

回答by pgras

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

您不需要自己计算文件名,请查看File.createTempFile

From the javadoc:

从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.

在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称。如果此方法成功返回,则可以保证:

  1. 在调用此方法之前,返回的抽象路径名表示的文件不存在,并且
  2. 此方法及其任何变体都不会在虚拟机的当前调用中再次返回相同的抽象路径名。

此方法仅提供临时文件工具的一部分。要安排自动删除此方法创建的文件,请使用 deleteOnExit() 方法。