简体   繁体   English

Java,使用数据和时间创建文件名

[英]Java, Create file name using data and time

I'm trying to create a file name that uses the date and time from another class to name it, problem is the class is called every so often and when it is a new file is created. 我正在尝试创建一个文件名,该文件名使用另一个类的日期和时间来命名它,问题是该类经常被调用,并且在创建新文件时会被调用。 I just wanted to create the file once and then write to it all the time. 我只想创建一次文件,然后一直写入。 Is it possible to do this as I can't work out how to? 我无法解决该怎么办?

Many thanks for any help in advance! 非常感谢您的任何帮助!

public void fileOutputToFile(String hex) throws Exception{

    dateAndTime dat = new dateAndTime();
    String date = dat.currentDateAndTime();

    String fileInfo = hex;
    String fileName = (date+".tsv");

    try{
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
        out.print(fileInfo);
        out.print("\t");
        out.close();
    }catch (IOException e){
    }
}

Use a date formatter like SimpleDateFormat to format the date to a string, eg "yyyy" to make a file 2011.tsv. 使用日期格式化程序(如SimpleDateFormat将日期格式化为字符串,例如“ yyyy”以创建文件2011.tsv。 Note that this requires a Date object to be returned. 请注意,这需要返回一个Date对象。

If you don't want to use a file based on date, store the filename somewhere. 如果您不想使用基于日期的文件,请将文件名存储在某处。 But why would you then use the date as the filename in the first place? 但是,为什么首先要使用日期作为文件名呢?

Edit: For a new file every hour, use a format like this: yyyy-MM-dd_HH (would result in 2011-03-29_17.tsv for example). 编辑:对于每小时一个新文件,请使用以下格式: yyyy-MM-dd_HH (例如,结果将在2011-03-29_17.tsv中显示)。

On the first call, you could store the filename as a member of the class. 在第一个调用中,您可以将文件名存储为类的成员。

You can append to the file on subsequent calls by using the FileWriter constructor: 您可以使用FileWriter构造函数在后续调用中追加到文件:

 public FileWriter( String fileName,
                    boolean append)

If you write frequently, an alternative is to keep the file open, storing the PrintWriter as a member. 如果您经常进行书写,另一种方法是保持文件打开,并将PrintWriter作为成员存储。 However, this may preclude some external interactions with the file in between writes. 但是,这可能会阻止两次写入之间与文件的某些外部交互。

Can you save the file name in session? 您可以在会话中保存文件名吗? if the file name exists in session use that other wise create it from another clases.. 如果文件名存在于会话中,则使用另一种方式从另一个小节创建它。

The problem with using the time alone is you can have still have multiple creates created at the same time. 仅使用时间的问题是您仍然可以同时创建多个创建。

You can do the following. 您可以执行以下操作。

// not thread safe.
private static final DateFormat DF = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS")

File file;
do {
    file = new File(DF.format(new Date())+".tsv");
} while(!file.createNewFile());
FileUtils.writeStringToFile(file, hex+"\t");

The other problem is that you will giving the file a new name on every update. 另一个问题是您将在每次更新时为文件指定一个新名称。 If youw ant to keep the same file name you need to set this in a different method of lazy initialise the value from a field. 如果要保留相同的文件名,则需要以另一种懒惰的方法设置此文件名,以初始化字段中的值。

In order to avoid creating a new file with a new date and time every time a client application invokes method fileOutputToFile() , move all lines up to and including the creation of the PrintWriter to the constructor so that the constructor opens the file just once and method fileOutputToFile() appends fileInfo to the output stream. 为了避免每次客户端应用程序调用方法fileOutputToFile()时都使用新的日期和时间创建新文件,请将所有行移至fileOutputToFile()包括PrintWriter的创建fileOutputToFile() ,包括构造PrintWriter ,以便构造函数只打开一次文件,然后方法fileOutputToFile()fileInfo附加到输出流。

Make sure to add a method close() that closes the PrintWriter stream by invoking out.close() . 确保通过调用out.close()添加一个close()方法来关闭PrintWriter流。

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class MyLoggingClass {
    private PrintWriter out;

    public MyLoggingClass() throws IOException {
        dateAndTime dat = new dateAndTime();
        String date = dat.currentDateAndTime();
        String fileName = (date + ".tsv");
        out = new PrintWriter(
                new BufferedWriter(new FileWriter(fileName, true)));
    }

    public void fileOutputToFile(String hex) {
        String fileInfo = hex;
        out.print(fileInfo);
        out.print("\t");
    }

    public void close() {
        out.close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM