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());
        }
    }
}
Peter David Carter
  • 2,548
  • 8
  • 25
  • 44
Dipak Patel
  • 41
  • 1
  • 9
  • write it as a String (write(a + "", 0, 1)). But there probably is a cleaner solution – Reinard Apr 11 '16 at 21:55
  • 1
    [Read the Javadoc](https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#write(int)) for the `write` method you are invoking. – Andy Turner Apr 11 '16 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! – Debosmit Ray Apr 11 '16 at 21:56

1 Answers1

-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.

stuart
  • 1,005
  • 1
  • 10
  • 18
  • 2
    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. – Andy Turner Apr 11 '16 at 22:04
  • 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 – stuart Apr 11 '16 at 22:29