I have to write both PrintWriter and DataOutputStream to print data onto my file. But PrintWriter is getting printed earlier than DataOutputStream though it comes after DataOutputStream in code.
Part of code:
import java.io.*;
import java.util.*;
public class file {
public static void main(String[] args) {
DataOutputStream dos=null;
PrintWriter pw=null;
try {
File f=new File("file.txt");
dos=new DataOutputStream(new FileOutputStream(f));
pw=new PrintWriter(f);
Scanner b=new Scanner(System.in);
for(int i=0;i<=4;i++) {
int h=b.nextInt();
b.nextLine();
dos.writeInt(h);
String s=b.nextLine();
int l=s.length();
dos.writeBytes(s);
pw.println();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if(dos!=null)
try {
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
pw.flush();
}
}
}
new line from pw is getting printed first and then data from dos.write(); how to avoid this?? and make it get in order?
Never mix a Writer and an OutputStream as they are used for different purpose, indeed a Writer is used to generate a text file (readable by a human being) and an OutputStream is used to generate a binary file (not readable by a human being), use only one of them according to your requirements.
Assuming that you decide to use only the DataOutputStream simply replace pw.println() with something like dos.write(System.lineSeparator().getBytes(StandardCharsets.US_ASCII)) to write the line separator into your file with your OutputStream. However please note that in a binary file adding a line separator doesn't really make sense since the file is not meant to be read by a human being.
Related
I have written some information into a .data file
PrintWriter out;
DataOutputStream binaryFile= null;
public WriteToFile(String file,String text ) throws IOException {
binaryFile= new DataOutputStream(
new FileOutputStream(file,true));
binaryFile.writeInt(2);
binaryFile.writeDouble(3);
binaryFile.writeChar(2);
binaryFile.writeUTF(text);
binaryFile.close();
}
I'm looking for a way to make a function that takes a .data file and writes each and every value into a corresponding text file
So Far I've tried this :
public void writeToTextFile(String myFile)
{
DataOutputStream fichIn = new DataOutputStream(new FileOutputStream(myFile));;
try {
//How to take information from .data file and writethem in text file ?
} catch (IOException e) {
System.out.println("Error");
}
// Some Code
}
You need to read your binary file with a DataInputStream and the readXXX() methods corresponding to the writeXXX() methods you used to write it, and then use the methods of PrintWriter to write to the new text file.
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
I am trying to generate random numbers as ids, and save them in a file to easily access them. I am currently using BufferedWriter in order to write these to the file, but the problem is that I am not too sure about how to go about finding where I should start writing into the file. I am currently trying to use BufferedReader to figure out where the next line is to write, but I am not sure how I am supposed to save this offset or anything, or how a new line is represented.
void createIds(){
File writeId = new File("peopleIDs.txt");
try {
FileReader fr = new FileReader(writeId);
BufferedReader in = new BufferedReader(fr);
FileWriter fw = new FileWriter(writeId);
BufferedWriter out = new BufferedWriter(fw);
String line;
while((line = in.readLine()) != null){
//How do I save where the last line of null is?
continue;
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
If you simply want to add IDs to the end of the file, use the following FileWriter constructor:
FileWriter fw = new FileWriter(writeId, true);
This opens the FileWriter in append mode, allowing you to write output to a pre-existing file.
If you would like to write the IDs to a particular location within an existing file rather than just to the end, I am not sure if this is possible without first parsing the file's contents.
For more information, see the JavaDoc for FileWriter.
We need more information about the file itself: what are you searching for with BufferedReader?
If the file is empty/newly created then you don't need BufferedReader at all. Just create the PrintWriter and save your numbers.
I'm just guessing here, but I think the real problem is that you're not sure how to generate random numbers (since this doesn't appear in your example code).
Here's some example code that'll write random numbers into a text file:
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Example
{
public static void main(String[] args)
{
Random r;
PrintWriter writer;
r = new Random();
try
{
writer = new PrintWriter(new BufferedWriter(new FileWriter("Examplefile.txt")));
for (int i = 0; i < 10; i++)
writer.println(Integer.toString(r.nextInt(10)));
writer.close();
}
catch (IOException e)
{
}
}
}
You can do
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File("abc.txt"),true)));
writer.append("test");
} catch (IOException e) {
e.printStackTrace();
}
everything in the question is in the title.
there's a lot of gibberish after "my name" in the output.
import java.io.*;
public class DOStry {
public static void main(String[] args) {
String file = "file.txt";
String stra = "my name";
int intb = 1;
double douc = 2.5;
char chad = 'f';
try
{
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeUTF(stra);
//i don't know why it prints gibberish after my name.
dos.writeInt(intb);
dos.writeDouble(douc);
dos.writeChar(chad);
dos.flush();
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
i'm not good, what have i missed? i'm just trying to learn DataOutputStream.
DataOutputStream is for printing binary, not text and you must read it as a binary file to make sense of it. The fact you can read portions of it as if it were text doesn't mean it is.
I suggest you do the following. These can all be read as text.
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println(stra);
pw.println(intb);
pw.println(douc);
pw.println(chad);
dos.close();
In short, if you mix binary and text, you are more likely to get yourself confused.
Sample Code is :-
import java.io.*;
public class WriteInt{
public static void main(String [] args)
{
WriteInt obj = new WriteInt();
obj.write();
}
public void write(){
File file = null;
FileOutputStream out = null;
int [] arr = {6};
try{
file= new File("CheckSize.txt");
out = new FileOutputStream(file);
for(int i =0; i<arr.length;i++)
{
System.out.println("Trying to write to file:-"+ file);
out.write(arr[i]);
}
}
catch(IOException ioex){
ioex.printStackTrace();
}
finally{
if(out != null)
{
System.out.println("Closing the stream");
try{
out.close();
}
catch(IOException ioex){
ioex.printStackTrace();
}
}
else{
System.out.println("Stream not open");
}
}
}
}
Since I am using Byte-Oriented Stream to write data to a file; My Question is that will the data be written to file in 4 steps (1 byte) in each step. Considering int to be of 4 bytes. Please correct me if I am wrong.
out.write(arr[i]) will write only the lowest byte of int. The best solution is to use java.io.DataOutputStream which has writeInt(int) method.
DataOutputStream out = new DataOutputStream(new FileOutputStream("file"));
out.writeInt(arr[i]);
In your example you are using OutputStream.write(int)
which writes only byte representation of provided number - only one byte is writen, take a look to OutputStream API. So your file will contain only one byte with 6. If you will try to write a number that is more than 255 - you can expect an exception.
Basically OutputStream requires its subclasses to implement only write(int) method, so other OutputStream methods sends theirs bytes to write(int). However all write methods in FileOutputStream are overridden and utilizes buffered native call that probably tries to send all data at a time.
I created a file named 'test.txt' and then took input from the user to write the input to the file. Everything runs fine. The program doesn't show any error at all. The file is created and the program takes input from the user but when I checked the content of the file, it was empty. Can anyone figure out what is wrong with my code? The code is as follows.
package InputOutput;
import java.io.*;
public class CharacterFileReaderAndFileWriter{
private BufferedReader br = null;
private BufferedWriter bw = null;
private PrintWriter pw = new PrintWriter(System.out, true);
public File createFile() throws IOException{
File f = new File("test.txt");
return f;
}
public void writeToFile() throws IOException{
try{
bw = new BufferedWriter(new FileWriter(createFile()));
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
//take input from the console (user)
br = new BufferedReader(new InputStreamReader(System.in));
String s;
pw.println("Please enter something");
pw.println("To stop the program, enter 'stop'");
do{
s = br.readLine();
if(s.compareTo("stop")==0)
break;
s+= "\r\n";//adding an new line to the string s
bw.write(s);
}
while(s.compareTo("stop")!=0);
br.close();
bw.close();
}
public static void main(String[] args) throws IOException{
CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();
cfr.writeToFile();
}
}
Most example programs show that you have to call.flush() on your BufferedWriter before the .close(). This should not be required, .close() should call .flush() automatically, but it doesn't hurt. Also you should call all the Stream/Writer objects .close() methods in reverse order as well, again correctly written classes should call .close() on all the object they wrap, but it doesn't hurt to do it anyway.
Other things that might catch you out later:
if(s.compareTo("stop")==0)
should be
if ("stop".equalsIgnoreCase(s))
it is more efficient, eliminates the possibility of a NullPointerException on s, handles any case of stop and most importantly more idiomatic Java than using .compareTo()
s+= "\r\n";//adding an new line to the string s
bw.write(s);
should be
bw.write(System.getProperty("line.separator"));
bw.write(s);
The s+= creates intermediate objects and garbage that needs to be collected. Hard coding line endings is bad as well.
You need close the outputstream.
file.close();