Question

I have trouble writing int values to a file in my app. When I write strings to file,its doing great. I tried int values using ObjectOutputStream but only some weird symbols(group of them not even one) keep appearing. So I tried using DataOutputStream too but even that doesn't work. Here is my code snippet:

myExternalFile = new File(getExternalFilesDir(filepath), filename);    
FileOutputStream fos = new FileOutputStream(myExternalFile,true);
DataOutputStream dos = new DataOutputStream(fos);

private boolean checkAnswer() 
{
    EditText edit = (EditText) findViewById(R.id.feditText);
    String answer = edit.getText().toString();
    if(answer.equals(""))
    {
        Toast.makeText(this, "Enter solution before moving on to next", Toast.LENGTH_SHORT).show();
        return false;
    }
    try
    {
        int qno = f.getQno();
        //ObjectOutputStream oos = new ObjectOutputStream(fos);
            //oos.writeObject(new Integer(qno));
        dos.writeInt(qno);
        dos.writeBytes(answer);
        dos.writeBytes(eol);//eol line separator already declared 
        dos.close();
    }
    catch (IOException e) {
         e.printStackTrace();
     }

    return true;
}

So everything else in the above code is doing fine...only int values are putting up a fight..So can anyone help me?? Thanks in advance!!!

Was it helpful?

Solution

DataOutputStream is not supposed to write textual files. Instead you use it to convert the standard java primitive type to bytes, therefore writing it compactly.

This results in a binary file, which you are not supposed to read.

If you want to read it, you would have to format the number as text (e.g. Integer.toString). The disadvantage is that this can require signifantly more space, depending on the value and the base.

Formatted in decimal as 2147483647 it would require 10 byte, whilst in binary it would constantly consume 4 byte. Note that values with only three digits require less space.

You could use the DataOutputStream to write the number in textform:

dos.writeBytes(Integer.toString(yourNumber));

If you really want to write a text file, you should use the BufferedWriter:

BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"));
writer.write("Whatever text.");
writer.write(Integer.toString(42));
writer.newLine();
writer.close();

If you wan't to parse it, you probably want to have a look at Scanner.

However, from guessing what you wan't to do, that might be what you need. I guess you want to store the state of your quiz-like app, in this case the answers.

There are numerous easier ways to achieve that:

  • Serialization
    • You can use the standard, if it doesn't prove too slow
  • Writing the file in binary
    • Should be easier because of the fixed length of primitive values, using DataOutputStream.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top