-4

How to read a .dat file in Java and write that data from that file into a text file? The 101.dat is a binary file.

DataOutputStream dos = new DataOutputStream(new FileOutputStream( "101.dat")); System.out.println("result " + dos.size()); 
for (int i = 0; i < 100; i++) { 
   dos.writeInt(i); 
   System.out.println(i); 
} 
dos.close();

The dos.size() method is giving me size 0. But the size should be something

jaind12
  • 123
  • 1
  • 12
  • What have you tried? What is the specific problem you are facing? Give us more information and your code, then we will be able to help and your question will not be downvoted or ignored. – ewanc Feb 12 '16 at 10:48
  • DataOutputStream dos = new DataOutputStream(new FileOutputStream( "101.dat")); System.out.println("result " + dos.size()); for (int i = 0; i < 100; i++) { dos.writeInt(i); System.out.println(i); } dos.close();} – jaind12 Feb 12 '16 at 10:53
  • DataOutputStream dos = new DataOutputStream(new FileOutputStream( "101.dat")); System.out.println("result " + dos.size()); for (int i = 0; i < 100; i++) { dos.writeInt(i); System.out.println(i); } dos.close(); } – jaind12 Feb 12 '16 at 10:53
  • Apology for not providing the code. – jaind12 Feb 12 '16 at 10:53
  • the dos.size() method is giving me size 0. But the size should be something – jaind12 Feb 12 '16 at 10:54
  • 1
    Possible duplicate of [How to open a .dat file in java program](http://stackoverflow.com/questions/3373155/how-to-open-a-dat-file-in-java-program) – Plebsori Feb 12 '16 at 11:21
  • that's a good point in the question linked to above. @jaind12 Can you update the question with the format of the file (binary, text, etc)? – ewanc Feb 12 '16 at 11:37

1 Answers1

0

You are using a DataOutputStream, which is for writing data to a file, not reading from file. You can use a DataInputStream for this. The following code snippet shows an example of reading from and writing to files:

  //writing string to a file encoded as modified UTF-8 
  DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
  dataOut.writeUTF("hello");      

  //Reading data from the same file
  DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));       

  while(dataIn.available()>0){

     String k = dataIn.readUTF();
     System.out.print(k+" ");
  }

The above example is from this tutorial.

ewanc
  • 1,284
  • 1
  • 12
  • 23
  • apologies, I accidentally wrote that as an answer instead of a comment. I had to undelete and edit in order to write an answer – ewanc Feb 12 '16 at 11:05