I'm writing an application that is supposed to act like a cafe clip card. In other words, for every n:th (10 in my case) coffee that a customer purchases, he/she is awarded a free beverage. So, I'm quite done with the loop and I've been working on writing and reading from a file since I need the program to remember where it last left off in order for the customer to be able to close the application once he/she has been in the store. However, I'm having a difficult time figuring out how to write and read from a file, the code I have doesn't seem to output any .txt file. I need the code to have a closing condition, and upon entering this condition, it should write the "count" to a .txt file, and shut down. Once the program is being run the next time it should read from this .txt file so it knows where the count is at.
Here's what I have so far:
public class FelixNeww {
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
entry = key.nextLine();
if(entry.compareTo(password) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
}
if(count == 10 && count != 0){
System.out.println("YOU'VE GOT A FREE COFFE!");
count = 0;
}
if(entry.compareTo(password) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
public void saveToFile(int count)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("countStorage.txt"))));
bw.write(count);
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bw != null)
{
try
{
bw.close();
}
catch(IOException e) {}
}
}
}
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(newInputStreamReader(newFileInputStream(new File("countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e) {}
}
}
return 0;
}
}
I see a few problems here. In your readFromFile() method, put a space after the keyword new. I also suggest putting a an absolute path for now (for debugging):
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
In your saveToFile() method, the constructor is wrong. Also put the full path to the file here:
bw = new BufferedWriter(new FileWriter("C:\\Temp\\countStorage.txt"));
Finally, in your saveToFile() method, write the count as a String. Writing it as an int refers to the Unicode character:
bw.write(Integer.toString(count)); //updated per Hunter McMillen
And invoke it...
FelixNeww f = new FelixNeww();
f.saveToFile(44);
System.out.println(f.readFromFile());
You need to invoke readFromFile or saveToFile in the place needed in order to become executed.
I suggest that you call readFromFile on the beginning of the Main method, use its returning contents, and saveToFile in the loop whenever the desired state changes and it needs to be saved.
Related
i am trying to make a highscore for a hangman game. So i need to save it so it doesnt restart everytime u start the game or return to the menu.. so I have a playstate that records the wins and losses at the end of the game and if the user leaves before solving it adds a loss. I found a tutorial to save via a SavaData file.. the problem is it saves an empty file nothing in there but has 2 empty lines.. and so i get a numberformatexception null.. i had it working before but it still would not read the line and would return an error numberformatexception Integer.parseInt.. I know the problem is in reading lines and now i dont know what went wrong please help me .. whats wrong with the code?? thanx
this is the saving code...
private void createSaveData() {
File file = new File(saveDataPath, filename);
try {
FileWriter output = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(output);
writer.write("" + 0);
writer.newLine();
writer.write("" + 0);
} catch (Exception e) {
e.printStackTrace();
}
}
private void setScores() {
FileWriter output = null;
try {
File F = new File(saveDataPath, filename);
output = new FileWriter(F);
BufferedWriter writer = new BufferedWriter(output);
writer.write(wins);
writer.newLine();
writer.write(losses);
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
private void loadScores() {
try {
File F = new File(saveDataPath, filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(F)));
String line = reader.readLine();
line = reader.readLine();
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
i then add loadScore(); at the begging of the playstate.. and setScore(); after a win++ or a loss++..
i have another highscorestate that calls on playstate and gets the wins and lossess as an integer and that works no problems cause it draws 0 , 0 .
in my render method i have this if the tries are too much or if the correct answer is guessed...
if (tries == 6) {
currentWord = ranWord;
execcurrentframe.setRegion(eman.ExecLoss.getKeyFrame(elapsedTime, false));
hangcurrentframe.setRegion(hman.hangdead.getKeyFrame(elapsedTime, false));
Wordsfont.draw(batch, "Game Over", eman.getPosition().x + 60, hman.getPosition().y + 70);
batch.draw(fu, 160, 510);
if (leverpressed == false){
bksound.stop();
lever.play();
leverpressed = true;
}
if (lossrecorded == false) {
losses += 1;
System.out.print("Losses = " + losses);
setScores();
lossrecorded = true;
}
}
else if (CorrectAnswer == true) {
hangcurrentframe.setRegion(hman.hangwin.getKeyFrame(elapsedTime, false));
Wordsfont.draw(batch, "You Won", eman.getPosition().x + 60, hman.getPosition().y + 70);
if (winrecorded == false) {
bksound.stop();
victory.play();
wins += 1;
System.out.print("Wins = " + wins);
setScores();
winrecorded = true;
}
}
I would suggest the following changes.
Use a single writeSaveData method. The code between createSaveData and setScores is largely duplicated. Also, use the Integer.toString() to write the output. Also, ensure the stream is closed (here using try with resources).
private void writeSaveData(int wins, int losses)
{
File file = new File(saveDataPath, filename);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(Integer.toString(wins));
writer.newLine();
writer.write(Integer.toString(losses));
}
catch (Exception e) {
e.printStackTrace();
}
}
There is an extra readLine() in the loadScores() method. Remove that extra line. Change to use try with resources.
private void loadScores()
{
File file = new File(saveDataPath, filename);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
String line = reader.readLine();
// line = reader.readLine() <-- REMOVE THIS LINE
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
reader.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
EDIT: If one cannot use try with resources, then the following approach may be used instead.
private void loadScores()
{
File file = new File(saveDataPath, filename);
BufferedReader reader = null;
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = reader.readLine();
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
A similar modification may be made to the suggested writeSaveData() or other methods.
You have overlooked one important part of the original createSaveData method:
writer.write("" + 0);
See that "" + 0? It effectively converts the integer to a string (though there are more elegant ways of doing this).
BufferedWriter has overloaded write method. This means there is a different method that is called when the parameter is a String, and a different one when the parameter is an int.
You have called the version whose parameter is an int. Its documentation says:
public void write(int c) throws IOException
Writes a single character.
Overrides:
write in class Writer
Parameters:
c - int specifying a character to be
written
Throws:
IOException - If an I/O error occurs
This tells you that it considers the int that you passed as a character. That is, if you give it the int 65, it will be taken as the character A. If you give it the int 48, it will be taken as the character 0.
If you give it the integer 0, this is the NUL control character.
When you read that back as a string, it is taken as a single-character string containing the NUL character. Of course, that's not a valid string format for a number.
So replace
writer.write(wins);
With
writer.write(String.valueOf(wins));
And do the same for losses.
I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is my input file:
This is a file test.
please take
notice of it.
Peace.
and this is the output:
This is a file test.
please take
notice of
I do not understant why it stops and "it." ,but it displays the word "test.".
Here's the code:
import java.io.*;
import java.util.*;
public class FileTest {
public static void readFile() throws Throwable {
File _output = new File("output.txt");
FileWriter _filewr = new FileWriter(_output);
BufferedWriter _buffwrt = new BufferedWriter(_filewr);
FileInputStream f = new FileInputStream(
"C:\\Users\\Diana\\Desktop\\FileTest\\test.txt.txt");
BufferedReader _buffer = new BufferedReader(new InputStreamReader(f));
String _str = _buffer.readLine();
while (_str != null) {
String[] _vect = _str.split(" ");
int i;
for (i = 0; i < _vect.length; i++) {
if (_vect[i].contains(".")) {
_buffwrt.write(_vect[i] + " ");
break;
}
else
_buffwrt.write(_vect[i] + " ");
_buffwrt.flush();
}
_str = _buffer.readLine();
}
}
public static void main(String[] args) throws Throwable {
readFile();
}
}
use another _buffwrt.flush(); outside the loop to flush anything remaining and don't forget _buffwrt.close(); at the end
update
#Svetlin Zarev mention a good point that only _buffwrt.close(); at the end will be sufficient to flush anything remaining
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close%28%29
The basic answer is, the break statement is breaking out of the loop, which is what you want, but it's also skipping the _buffwrt.flush(); statement. Because you're not closing the output streams correctly, the buffered content is simply been discard.
While you could put more flush statements in, it kind of defeats the purpose of BufferedWriter, instead, you should simply manage you resources better and make sure that they are getting closed when you are done with them, which will, in this case, flush the buffers before closing the resource.
File _output = new File("output.txt");
try (BufferedWriter _buffwrt = new BufferedWriter(new FileWriter(_output))) {
try (BufferedReader _buffer = new BufferedReader(new FileReader("test.txt"))) {
String _str = _buffer.readLine();
while (_str != null) {
String[] _vect = _str.split(" ");
int i;
for (i = 0; i < _vect.length; i++) {
if (_vect[i].contains(".")) {
System.out.println("1 " + _vect[i]);
_buffwrt.write(_vect[i] + " ");
break;
} else {
System.out.println("2 " + _vect[i]);
_buffwrt.write(_vect[i] + " ");
}
}
_str = _buffer.readLine();
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
Take a look at The try-with-resources Statement for more details
I have been working on this code for the day and am almost at the finish line. What I want is that the code should work as a clip card, remembering the number of purchased coffees, and awarding the customer a free coffee every 10th purchase. I'm writing to a file and reading from it in order for a customer to be able to continue his clip card where he left of last time. So to my problem...I have properly been able to write my "count" variable to a file, and it is storing it correctly. However, every time I run the program again it starts off a 0 and I don't see why. I need it to save the current count, and read the count once run again. For example, if a customer has previously purchased 7 coffees and is returning to the store, his counter needs to start at 7. For some reason it is not doing that.
Here's what I have so far:
public class FelixNeww {
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
FelixNeww f = new FelixNeww();
System.out.println(f.readFromFile());
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
entry = key.nextLine();
if(entry.compareTo(password) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
f.saveToFile(count);
}
if(count == 10 && count != 0){
System.out.println("YOU'VE GOT A FREE COFFE!");
count = 0;
}
if(entry.compareTo(password) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
public void saveToFile(int count)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("C:\\Temp\\countStorage.txt"))));
bw.write(Integer.toString(count));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bw != null)
{
try
{
bw.close();
}
catch(IOException e) {}
}
}
}
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e) {}
}
}
return 0;
}
}
You are currently setting your count variable to 0. You should set it to the value that's in the file. Do this just before the while loop:
count = f.readFromFile();
while(true) {
You should also implement a way to gracefully exit the while loop. For example, if the user enters "q", you can execute the break; statement to exit the while loop. And after your while loop, call key.close(); to close the Scanner object.
The scope of count variable is local in both instances
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
System.out.println(f.readFromFile());
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
In the readFromFile function, you read it from the file, return it, but don't keep track of it in a variable, why don't you replace the println with this inside your main:
count=f.readFromFile
I'm tinkering around on a small application to read some numbers in from a file. Everything runs well so far, but now I have encountered a problem I don't know how I can effectively fix it. If the user enters, unintentionally maybe, the wrong filename a FileNotFoundException will be thrown by the JVM, that I catch in my invoking method. Now I want to give him (the user) two another tries to enter the correct filename, but I don't know how I can invoke the method again which is opening the file when I'm actually in the catch-block below.
I will illustrate my transient solution below, but I'm not really sure if this is the most effective/elegant way to solve this problem:
//code omitted
int temp = 0;
while(true) {
filename = input.next();
try {
ex.fileOpen(filename);
}
catch(FileNotFoundException e) {
if(temp++ == 3) {
System.err.println("You have entered the filename three times consecutively wrongly");
return;
}
continue;
}
break;
}
//do some other stuff
input is a scanner which reads the user input and assigns it to the String-variable filename. fileOpen is a method which takes a filename, opens the file, reads the content and write all numbers in a vector.
So, I would really appreciate every support from the more experienced java programmers.
Greetings
Tom
You could use something like this,
public class AppMain {
public static void main(String[] args) throws IOException {
String filePath = input.next();
InputStream is = getInputStream(filePath);
int temp = 0;
while(is == null && temp < 3){
filePath = input.next();
is = getInputStream(filePath);
temp++;
}
if(is == null){
System.err.println("You have entered the filename three times consecutively wrongly");
return;
}
.........
.........
}
private static InputStream getInputStream(String filePath){
InputStream is = null;
try{
is = new FileInputStream(filePath);
return is;
}catch (IOException ioException) {
return null;
}
}
}
You may want to recursively call the method again:
public void doTheStuff(int attemptsLeft)
// ...
if (attemptsLeft == 0) {
System.err.println("You have entered the filename three times consecutively wrongly");
return;
}
filename = input.next();
try {
ex.fileOpen(filename);
}
catch(FileNotFoundException e) {
doTheStuff(attemptsLeft - 1);
return;
}
// ...
}
then simply call doTheStuff(3)
You can use exists method of the File class
For example fileOpen method can return true/false whether file exists
Think this will work.
int x = 0;
while (true){
filename = input.next();
try{
ex.fileOpen(filename);
break; // If it throws an exeption, will miss the break
}catch(FileNotFoundException e){
System.err.println("File not found, try again.");
}
if (x==2){
System.errprintln("You have entered the wrong file 3 times");
System.exit(0);
}
x++
}
Do not use exceptions to control your WorkFlow. Try something like this:
final int MAX_ERROR_ALLOWED=3;
public void readFile(String filename, int errorCount){
try{
File f = new File(filename);
if(!f.exists()){
String newFilename = input.next();
if(errorCount>=MAX_ERROR_ALLOWED){
throw new JustMyException();
}
readFile(newFilename, errorCount++);
}else{
//whatever you need to do with your file
}
}
}
How about something like this (pseudocode, not executable)?
// ...
for(int i = 0; i < 3; i++)
{
// User interaction to get the filename
if(attemptToOpenFile(ex))
{
break;
}
}
// Check if the file is open here and handle appropriately.
// ...
}
bool attemptToOpenFile(File ex, String filename) { // Forgot the class name for this
try {
ex.fileOpen(filename);
return true;
} catch(FileNotFoundException e) {
return false;
}
}
Alternatively, check if the file exists before calling fileOpen().