I got a folder called DIR and a subfolder called SUB.
the java file i am running is placed in the DIR folder, and now i want to save my small string in a .txt file in the SUB folder.
Could you help me?
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("SUB/myfile.txt")));
out.println("simpleString);
out.close();
This simple task seems very complicated in Java. The reason is, that you can configure everything on the way from the String to the file. You could e.g. specifiy the encoding of the output file, which defaults to platform encoding (e.g. "win1252" for Windows in most parts of the western hemisphere). To write UTF-8 files use:
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("SUB/myfile.txt"),"UTF-8"));
out.println("simpleString);
out.close();
The PrintWriter also has a "flush immediately" option, which is nice for logfiles you want to monitor in the background.
By chaining the IO constructors, you can also increase performance when using a BufferedWriter, because this flushes only to the disk, when a minimum size is reached, or when the stream is closed.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("SUB/myfile.txt"),"UTF-8")));
out.println("simpleString);
out.close();
By having to create a FileOutputStream you specify the output should go to the disk, but you can also use any other streamable location, like e.g. an array:
byte[] bytes = new byte[4096];
OutputStream bout = new ByteArrayOutputStream(bout);
PrintWriter out = new PrintWriter(
new OutputStreamWriter(bout,"UTF-8"));
out.println("simpleString);
out.close();
You will love Javas versatility!
Apache org.apache.commons.io.FileUtils class is implemented to reduce amount of boilerplate code..
FileUtils.writeStringToFile(new File("SUB/textFile.txt"),stringData,"UTF-8");
Related
I'm using txt files, creating them with the class PrintWriter. This allows me to print inside a txt file some content using println(...) method.
But now I need to add some content at the end of the list that I created. Like this:
PrintWriter writer = new PrintWriter("File.txt", "UTF-8");
writer.println("Hello");
writer.println("Josh!");
writer.close();
the result is a file like this:
Hello
Josh!
but what if I would like to add new words at the bottom of the text? I would prefer an overwriting of the file "File.txt" with the content updated?
Hello
Josh!
How are you?
I was thinking on something like, "Ok I have to add another line at the end, so read all the file, and write another file (with the same name and content) adding a new line at the end", but it seems too strange to do, I feel like there is another simple way to do it. Any other idea?
You could simply use a FileWriter instead, it has an append mode that you can enable:
FileWriter writer = new FileWriter("File.txt");
writer.write("Hello\n");
writer.write("Josh!\n");
writer.close();
writer = new FileWriter("File.txt", true);
writer.append("Great!");
writer.close();
Your suspicions are correct.
You should use try with resources (Java 7+):
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("File.txt", true)))) {
out.println("How are you?");
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file). Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out. But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
Also this allows you to append to a file, rather than replacing the whole file, on every run. Lastly, try with resources means you do not have to call .close(), it's done for you! Grabbed from here
I have code that creates a PrintWriter and prints Unicode symbols
out = new PrintWriter(new FileWriter("test.txt"));
out.print("\u2588");
out.close();
It works perfectly while saved with UTF-8 encoding inside eclipse, but when I export it to a jar it just prints off question marks. How would I tell it to use UTF-8 when printing off strings?
Eclipse may be helping you to create UTF-8 encoded file but it is better to use the right encoding in your code as well.
FileWriter does not take any parameter for encoding. You can use OutputStreamWriter as it accepts the encoding also. You may change your PrintWriter initialization to:
PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream("test.txt"),"UTF-8")));
Instead of FileWriter, create a FileOutputStream. then wrap this in an OutputStreamWriter, It allows you to pass an encoding in the constructor.
FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")
PrintWriter out = new PrintWriter(osw);
I'm using something like this in a java application to write to a file:
BufferedWriter out = new BufferedWriter(new FileWriter(out1, true)); //where out1 is a File.
When I run it from netBeans the output is good. When I try to run it from the windows command line (the intended use; using the jar) the accented characters go crazy. I think that is have something to do with the chars encoding.
e.g.
(the output file is a HTML one);
I want to write this:
"<p>Inclinação(1):</p>"
Using Win command line, appears this:
<p>Inclina褯(1):</p>
Use OutputStreamWriter with FileOutputStream so you can explicitly specify the Charset.
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out1, true), "UTF-8"));
I believe that you need to specify an encoding, unfortunately FileWriter does not provide any ways to set it, though there are other options such as:
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(out1, true),"UTF-8"));
I resolve this problem using the parameter 8859_1, you can learn more about here
http://www.cafeconleche.org/books/xmljava/chapters/ch03s03.html.
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(baos, "8859_1"));
I have an exe packaged inside my jar file and I am trying to copy it to a temporary location so that i can run it using Desktop.browse(), to do this I set up a scanner with the input stream constructor using class.getResourceAsStream, and then with a printwriter wrote that all to a file. The problem that occurred says that the exe is invalid. I think this is due to some binary data being lost. If anyone can help please post a comment.
Scanner sc = new Scanner(ClassBuilder.class.getResourceAsStream("jd-gui.exe"));
File copy = new File("C://users//Owner//Desktop//java//jd-gui.exe");
copy.createNewFile();
PrintWriter writer = new PrintWriter(copy);
while(sc.hasNextLine())
writer.println(sc.nextLine());
writer.flush();
writer.close();
sc.close();
Desktop.getDesktop().browse(copy.toURI());
As already mentioned use streams for binary data. Commons io makes copying streams easy. Something like:
InputStream in = getClass().getResourceAsStream("jd-gui.exe");
OutputStream out = new FileOutputStream("jd-gui.exe");
IOUtils.copy(in, out);
I was handed some data in a file with an .dat extension. I need to read this data in a java program and build the data into some objects we defined. I tried the following, but it did not work
FileInputStream fstream = new FileInputStream("news.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
Could someone tell me how to do this in java?
What kind of file is it? Is it a binary file which contains serialized Java objects? If so, then you rather need ObjectInputStream instead of DataInputStream to read it.
FileInputStream fis = new FileInputStream("news.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
// ...
(don't forget to properly handle resources using close() in finally, but that's beyond the scope of this question)
See also:
Basic serialization tutorial
A .dat file is usually a binary file, without any specific associated format. You can read the raw bytes of the file in a manner similar to what you posted - but you will need to interpret these bytes according to the underlying format. In particular, when you say "open" the file, what exactly do you want to happen in Java? What kind of objects do you want to be created? How should the stream of bytes map to these objects?
Once you know this, you can either write this layer yourself or use an existing API (assuming it's a standard format).
For reference, your example doesn't work because it assumes that the binary format is a character representation in the platform's default charset (as per the InputStreamReader constructor). And as you say it's binary, this will fail to convert the binary to a stream of characters (since, after all, it's not).
// BufferedInputStream not strictly needed, but much more efficient than reading
// one byte at a time
BufferedInputStream in = new BufferedInputStream (new FileInputStream("news.dat"));
This will give you a buffered stream which will return the raw bytes of the file; you can now either read and process them yourself, or pass this input stream to some library API that will create appropriate objects for you (if such a library exists).
That entirely depends on what sort of file the .dat is. Unfortunately, .dat is often used as a generic extension for a data file. It could be binary, in which case you could use FileInputStream fstream = new FileInputStream(new File("news.dat")); and call read() to get bytes from the file, or text, in which case you could use BufferedReader buff = new BufferedInputReader(new FileInputStream(new File("news.dat"))); and call readLine() to get each line of text. [edit]Or it could be Java objects in which case what BalusC said.[/edit]
In both cases, you'd then need to know what format the file was in to divide things up and get meaning from it, although this would be much easier if it was text as it could be done by inspection.
Please try the below code:
FileReader file = new FileReader(new File("File.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
temp = br.readLine();
System.out.println(temp);
}
A better way would be to use try-with-resources so that you would not have to worry about closing the resources.
Here is the code.
FileInputStream fis = new FileInputStream("news.dat");
try(ObjectInputStream objectstream = new ObjectInputStream(fis)){
objectstream.readObject();
}
catch(IOException e){
//
}