0

Pretty sure this should be really easy, but I can't write to a file. No I/O exception is thrown nothing. I was having a similar problem reading earlier and I tried a hundred different ways until

DataInputStream dis = new DataInputStream(reading.class.getResourceAsStream("hello.txt"); BufferedReader input = new BufferedReader(new InputStreamreader(dis));

this worked! and I could use scanners and such to read from this point.

FileReader, making File file = new File("hello.txt") whatever, none of that worked. I couldn't get any of it to even throw an error when it was an incorrect file name.

Now I have the same problem except for writing to a file but there's no equivilant to reading.class.getResourceAsStream("hello.txt"); that makes an /output/ stream.

Does anyone know how to get the "ResourceAsStream" but as an output stream, /or/ does anyone know what my problem might be?

I know a lot of people on this website have reading/writing issues but none of the posts helped me. note - yes I was closing, yes I was flushing, yes I had code that wrote to the file.

Dylan Kidd
  • 162
  • 4
  • 15
  • 1
    What is the context? Are you trying to read from and write inside a `jar` file? – merlin2011 Oct 21 '15 at 05:37
  • You might want to check the permissions on the directory that this is going to. Also if the file already exists you may want to check the permissions on this as well. – Dale Oct 21 '15 at 05:50
  • have you tried using [FileOutputStream](http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html) ? `FileOutputStream outputStream= new FileOutputStream(String file)` – codiacTushki Oct 21 '15 at 06:21
  • It's for a data structures assignment. It's not even the interesting or challenging part. There's a text file in my current package and I just want to read it. And there's another text file and I want to write to it, from a .java file. – Dylan Kidd Oct 22 '15 at 01:00

1 Answers1

0

GetResourceAsStream is meant to read resources (e.g. property files) that were distributed and packages along with the code. There's no guarantee they're in writable mode, e.g. both code and resources could be distributed as a jar, or jar-inside-a-WAR-inside-an-EAR...

See here Write to a file stream returned from getResourceAsStream() for additional discussion and a workaround suggestion, though it's not very recommended IMHO. I think the reasonable practice is to distinguish between (a) your immutable code distribution (b) data editable at runtime ... the latter could reside on a different machine, have different policies for secuirty/replicatoin/backup, etc.

Community
  • 1
  • 1
Pelit Mamani
  • 2,321
  • 2
  • 13
  • 11