0

Hello Java experts here is my question. I currently have a code that runs some queries and outputs the data into a csv file. It currently outputs it into my desktop and saves the files.

as you can see

//csv printer
PrintWriter pw = null;
try {

    pw = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\JChoi\\Desktop\\new Date().getTime() + data.csv")));
} catch (Exception e) {
    System.out.println("I could not open the output csv file, see stacktrace below:");
    e.printStackTrace();
}

although it printed the file, the file just came out to say "new Date().getTime()data.csv"

i guess im missing a step in setting the date and time. ultimately i want to get it so that when i run this file, i will get a new csv file with today's date and current time on the file. Thanks

EDIT: SOLVED

Date dNow = new Date( );
SimpleDateFormat timeStamp = 
new SimpleDateFormat ("yyyy-MM-dd");

//csv printer
PrintWriter pw = null;
try {
    pw = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\JChoi\\Desktop\\google api csv outputs\\" + timeStamp.format(dNow) +"_data.csv")));
}

thanks all

2 Answers 2

1

Basically

new FileWriter("C:\\Users\\JChoi\\Desktop\\new Date().getTime() + data.csv")));

Is creating a String literal (literally, making the text between the quotes what you type)

What you need to do is some variable/String concatenation, for example...

new FileWriter("C:\\Users\\JChoi\\Desktop\\" + new Date().getTime() + "data.csv")));

You should note, Date#getTime will return the number of milliseconds since the Unix epoch as a long. As such, you might want to consider using some kind of DateFormat to format the value into a more human readable format

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the response. so when i type in the new code i get an error that says "date cannot be resolved to type" could that be because i didnt define date()?
So you forget to import java.util.Date
0

The statement

new FileWriter("C:\\Users\\JChoi\\Desktop\\new Date().getTime() + data.csv")

Cretes file with name "C:\Users\JChoi\Desktop\new Date().getTime() + data.csv"

If you want to put actual date to file name, you should concat Strings like

new FileWriter("C:\\Users\\JChoi\\Desktop\\"+new Date().getTime() + +"data.csv")

1 Comment

thanks for the response. so when i type in the new code i get an error that says "date cannot be resolved to type" could that be because i didnt define date()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.