0

I want to store data in the created file, but my code stores binary language in the file instead. Can anyone help me to store a string?

import java.io.*;
import java.util.*;
class WriteToFileExample {
    public static void main(String args[]) {
        try {
            // Create file 
            FileWriter fstream = new FileWriter("out.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            Scanner sc = new Scanner(System.in);
            System.out.println("enter name");
            int a = sc.nextInt();
            out.write(a);
            out.close();
        } catch (Exception e) {


            //Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}
3
  • write it as a String (write(a + "", 0, 1)). But there probably is a cleaner solution Commented Apr 11, 2016 at 21:55
  • 1
    Read the Javadoc for the write method you are invoking. Commented Apr 11, 2016 at 21:56
  • you want a name, which, traditionally is a string, cause we don't name to people by numbers (i think), and then read it in using nextInt. fascinating! Commented Apr 11, 2016 at 21:56

1 Answer 1

-1

You're using Scanner.nextInt() to input a String. Change:

int a = sc.nextInt()

to

String a = sc.next()

The broader issue is that when you use the "write(int)" method in BufferedWriter, you're writing the character specified by the integer. What this means is that you're writing whatever ASCII character is represented by the integer you put in--for example, if you entered "65" in your code, you'd get a text file with a capital A in it, since A is ASCII #065.

Here's a table of the ASCII values for characters: http://web.cs.mun.ca/~michael/c/ascii-table.html

As you can see, the first 20 or so aren't letters or numbers like you'd think of them. If you want, you can try inputting the integer values for some of those characters into your code to see how it works.

Sign up to request clarification or add additional context in comments.

2 Comments

The reading isn't the issue per se. There is nothing wrong with reading an int, it is how that int is then written that is problematic.
You're right, but if someone is still using the Scanner class for this sort of thing then I'm not sure how helpful the Javadoc's description of "int specifying a character to be written" is. I edited the answer to elaborate more

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.