Store a file as an integer

C

cyclone771

Hi. I have recently started learning to program using Java, and I am
currently working on creating a counter. Right now I am working as an
application only, and would like to know how to get my program to open
a file (Already done, I think.) and get it to save the contents as an
integer, x. Any help would be greatly appreciated. Here is the source
code:

import java.io.*;

class counter {
public static void main(String[] args) throws IOException {
File inputFile = new File("counter.jvar");
File outputFile = new File("counter.jvar");

FileReader in = new FileReader(inputFile);
int x = in;
/* I know this(^^) line creates an error b/c of diff file types, but
how do I fix it? */
in.close();
int y = (x + 1);
System.out.println(y);
FileWriter out = new FileWriter(outputFile);
out.write(y);
out.close();
}
}
 
B

Bruce Lee

Hi. I have recently started learning to program using Java, and I am
currently working on creating a counter. Right now I am working as an
application only, and would like to know how to get my program to open
a file (Already done, I think.) and get it to save the contents as an
integer, x. Any help would be greatly appreciated. Here is the source
code:

import java.io.*;

class counter {
public static void main(String[] args) throws IOException {
File inputFile = new File("counter.jvar");
File outputFile = new File("counter.jvar");

FileReader in = new FileReader(inputFile);
int x = in;
/* I know this(^^) line creates an error b/c of diff file types, but
how do I fix it? */
in.close();
int y = (x + 1);
System.out.println(y);
FileWriter out = new FileWriter(outputFile);
out.write(y);
out.close();
}
}
You're better off using a FileInputStream and FileOutputStream for this.
The error is because you're saying the int x is a FileReader object which it
isn't - use the read() method instead. ie. int x = fileinputstream.read();
 
R

Roedy Green

You're better off using a FileInputStream and FileOutputStream for this.
The error is because you're saying the int x is a FileReader object which it
isn't - use the read() method instead. ie. int x = fileinputstream.read();

for character i/o, a Reader/Writer is correct. Using an
InputStream/OutputStream is deprecated for that purpose because of the
problems with encoding.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top