简体   繁体   中英

writing a file in directory using printwriter in java

file is not creating in my workspace or in any folder, can any one suggect specify a directory and also have to use "UTF-8"

PrintWriter writer = new PrintWriter("twitterData_"+currDate+".txt", "UTF-8");
            writer.println("TweetId,UserScreenName,Tweet,TimeStamp");

Add this line to your code to see in which directory the file is located:

System.out.println(System.getProperty("user.dir"));

That prints out the working directory of the java process.

The file was certainly created, unless new PrintWriter() threw an exception.

can any one suggest specify a directory

If that means 'how to specify a directory', prepend it to the filename. If it means 'how to discover the directory' the file was written in, print the value of System.getProperty("user.dir") .

and also have to use "UTF-8"

Is that a question?

public class PrinterQuestion {

    public static void main(String [] args){
        DateFormat format = new SimpleDateFormat("MMddyyyy");
        Date date = new Date();
        String currDate = format.format(date);
        try{
            //PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
            PrintWriter writer = new PrintWriter("twitterData_" + currDate + ".txt", "UTF-8");
            writer.println("TweetId,UserScreenName,Tweet,TimeStamp");
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}

If you are using a date formatted as 4/5/2010 then you would get an error because that path does not exist. If you are trying to save it in the current directory then you must change the date format as above to avoid the confusion of file path. This will put it in your workplace directory by the way, if you are using Eclipse that is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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