简体   繁体   中英

Get file that PrintWriter writes to

How do you get the name of the file that a PrintWriter object is writing to?

PrintWriter myPrintWriter = new PrintWriter(fileName, "UTF-8");

I need the fileName parameter.

You can't - it might not even be writing to a file, eg

StringWriter stringWriter = new StringWriter();
PrinterWriter printWriter = new PrintWriter(stringWriter);

If you need this information, you could potentially create a subclass of PrintWriter which remembers (and exposes) the file it's writing to... but usually the need to do this indicates that you're best off taking a look at your design and reconsidering it. (Personally I tend to avoid PrintWriter anyway, as I don't like exceptions just being swallowed, but that's a different matter.)

If you write to file, your can use this code:

File f = new File("some_file.txt");
f.createNewFile();
PrintWriter writer = new PrintWriter(new FileWriter(f));

Or you can use name of the file:

PrintWriter myPrintWriter = new PrintWriter("some_file.txt", "UTF-8");

If the file exists then it will be truncated to zero size; otherwise, a new file will be created.

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