Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the absolute path location for this OutputStream?

Tags:

java

byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
System.out.println("Created successfully"+os.getAbsolutePath());

This is my code.I have to get the location for "test.txt".please check it out if it is some other way to implement...?

like image 943
Prasanna M Avatar asked Oct 31 '25 14:10

Prasanna M


2 Answers

FileOUtputStream also has File constructor so you can use that.

File out = new File("test.txt");

OutputStream os = new FileOutputStream(out);
System.out.println("Created successfully "+out.getAbsolutePath());
like image 57
dkatzel Avatar answered Nov 03 '25 06:11

dkatzel


Getting this information after you've only got an OutputStream variable feels like the wrong approach to me. After all, there's no guarantee that an OutputStream is writing to a file at all - it could be a ByteArrayOutputStream or writing to a socket. You can get this information before you create the FileOutputStream though. For example:

File file = new File("test.txt");
System.out.println("Absolute path: " + file.getAbsolutePath());

Or

Path path = Paths.get("text.txt");
System.out.println("Absolute path: " + path.toAbsolutePath());

... then create the FileOutputStream based on that.

like image 21
Jon Skeet Avatar answered Nov 03 '25 05:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!