Read and Write to a file - java

I am having to make a gui project for my CSIS class and I am having trouble with the read and Write I am using. I am making a game where you battle stuff and after you beat five of them it shows a message saying "YOU WIN". Every time you win a battle, I have it write the number of wins to a file so if you were to close the game you can continue when it is opened again. Here is the code that i have Written - this is my read method.
private static int read()
{
int returnValue = 0;
try(Scanner reader = new Scanner("wins.txt"))
{
while(reader.hasNextLine())
{
String read = reader.nextLine();
returnValue = Integer.parseInt(read);
}
}
catch(NullPointerException e)
{
System.out.println("No such File! Please Try Again! " + e.getMessage());
}
return returnValue;
and this is my Write method.
private static void write(int wins)
{
try(Formatter writer = new Formatter("wins.txt");)
{
writer.format("%d", wins);
}
catch (FileNotFoundException e)
{
System.out.println("File not Found!!");
}
}
the only thing that is in the wins.txt file is the number that the Write method writes into it. so i win once then the file will have "1" and if i win twice then it will have "2"
Whenever I run the program, it throws a NumberFormatException. I am not sure why it is doing this because I am parseing the String that that reader reads into an int.

The problem is that this code...
Scanner reader = new Scanner("wins.txt")
... constructs a Scanner with the literal text "wins.txt", not the contents of the file "wins.txt".
To read a file with a Scanner, the easiest way for you is probably to construct it using a File object...
Scanner reader = new Scanner(new File("wins.txt"))
There are some other changes you will need to make to your code to get it to work from this point, but this should cover the major issue.

Related

How to use Constructor Scanner in java programming to grasp number of lines in text file

I was trying to remove the first line in text file using java code referencing from this link but still the scanner does not contain any text, so it write nothing in the text file, please help, what is then problem...?
here is a peace of code,
File path=new File("C:/Users/kassim Ismail/workspace/Coding/textdoc.txt");
Scanner scan=new Scanner(path);
FileWriter newread=new FileWriter("C:\\Users\\kassim Ismail\\workspace\\Coding\\textdoc.txt");
BufferedWriter newreader=new BufferedWriter(newread);
while(scan.hasNextLine()){
String nextline=scan.nextLine();
if(nextline.equals("\n")){
newreader.newLine();
}else{
newreader.write(nextline);
}
}
scan.close();
newreader.close();
newread.close();
}
Right now I don't see any mistake in your code (reader/writer should work). One thing I am unsure about is wether the blank space in your Filepath is problematic or not (Some programs can't work with blank spaces in file paths I am not sure about Java though).
Maybe you could add some System.out.println("") statements for debugging purposes. For Example (testing if the input file exists):
System.out.println("Inputfile exists: "+path.exists())
printing the read line:
System.out.println("Read line: "+nextline)
private boolean removeTopLine(File file){
try{
boolean status = false;
Scanner s = new Scanner(file);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
String content = "";
int counter = 0;
while (s.hasNextLine()){
if (counter > 0){
content += s.nextLine();
}
counter++;
}
writer.write(content);
writer.close();
status = true;
}
catch (Exception e){
e.printStackTrace();
}
return status;
}
This is a functional code snippet that would delete the first line of a file however there could be debate on efficiency.

Try Catch logic error with file i/o in Java

So, I've been trying to learn java from various sources, I've been learning for about 2 years now. So far everything has been going smoothly, i haven't had to post on stackoverflow for a while. Recently I've been trying to figure out how to create and read files with java. I can do both of those things in separate apps, but when i try to do both it doesn't always work.
What i want to happen:
I want my program to create data.txt, then I want it to read the data and produce an error log on error.txt.
What happens:
The data.txt file gets created as expected, but nothing is written to the error.txt file. I'm having trouble grasping the try/catch block and how exactly it works. Anyone got any ideas? even just some advice would be appreciated. Thanks!
import java.io.*;
import java.util.Scanner;
public class dataReader {
public static void main(String args[]) throws Exception {
File fileName;
fileName = new File("data.txt");
PrintWriter outputFile;
outputFile = new PrintWriter(fileName);
File errorFile;
errorFile = new File("errors.txt");
PrintWriter outputErrorFile;
outputErrorFile = new PrintWriter(errorFile);
Scanner inputFile;
int recordNumber = 0;
String inputData;
outputFile.println(77);
outputFile.println("Fred");
outputFile.println(92);
outputFile.println("Wilma");
outputFile.println(89.9);
outputFile.println("Barney");
outputFile.println(42);
outputFile.println("BettyS");
inputFile = new Scanner(fileName);
while (inputFile.hasNext()) {
recordNumber++;
try {
inputData = inputFile.nextLine();
if (Integer.parseInt(inputData) < 50) {
outputErrorFile.println(recordNumber + ", " + inputData + ", is less than 50.");
} else if (Integer.parseInt(inputData) > 90) {
outputErrorFile.println(recordNumber + ", " + inputData + ", is less than 50.");
}
} catch (Exception e) {
outputErrorFile.println(recordNumber + ", That's not an integer.");
}
}
outputFile.close();
outputErrorFile.close();
System.out.println("Program terminated.");
}
}
Move the outputFile.close(); line before inputFile = new Scanner(fileName);. Currently it's just cached in the memory and not written actually to the disk.
The documentation of PrintWriter says it all. The PrintWriter(Writer) constructor creates a writer which is not automatically flushed.
You have to call close or flush method to write your data to the file.
So you have to use outputFile.close(); method before starting reading.
and as a good practice you have to close all your PrintWriter instances to avoid memory leak.
just in this case please add inputFile.close(); at the end of your program.

program only read last line in .txt file java

I have a problem and don't know what to do. This method is supposed to read all the text in a .txt document. My problem is when the document contains more then one line of text and the program only read the last line. The program don't need to worry about signs like . , : or spaces, but it have to read all the letters. Can anybody help me?
example text
hello my name is
(returns the right result)
hello my
name is
(returns only name is)
private Scanner x;
String readFile(String fileName)
{
try {
x = new Scanner (new File(fileName + (".txt")));
}
catch (Exception e) {
System.out.println("cant open file");
}
while (x.hasNext()) {
read = x.next();
}
return read;
}
It's because when you use read = x.next(), the string in the read object is always being replaced by the text in the next line of the file. Use read += x.next() or read = read.concat(x.next()); instead.
You replace every read with every read(). Also, you didn't close() your Scanner. I would use a try-with-resources and something like,
String readFile(String fileName)
{
String read = "";
try (Scanner x = new Scanner (new File(fileName + (".txt")));) {
while (x.hasNextLine()) {
read += x.nextLine() + System.lineSeparator(); // <-- +=
}
} catch (Exception e) {
System.out.println("cant open file");
}
return read;
}

FileNotFoundException occurs due to my outputStream method

Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.

DataInputStream for input text files?

I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?
import java.io.*;
import java.util.*;
class ReadWriteData
{
public static void main(String[] args) throws Exception
{
//create ouput file
PrintWriter output = new PrintWriter("output2.txt");
DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));
try
{
// read data from file
while (true)
{
double number1 = file1.readDouble();
double number2 = file2.readDouble();
double result = number1 * number2 ;
output.println(result);
}
}
catch (IOException e)
{
System.err.println("Error");
System.exit(1);
}
output.close() ;
}
}
Here is an implementation with a BufferedReader that works.
public static void main(String[] args) throws Exception {
//create ouput file
PrintWriter output = new PrintWriter("output2.txt");
BufferedReader file1 = new BufferedReader(new FileReader("numbers1.txt"));
BufferedReader file2 = new BufferedReader(new FileReader("numbers2.txt"));
try {
// read data from file
while (true) {
String number1AsString = file1.readLine();
String number2AsString = file2.readLine();
if (number1AsString == null || number2AsString == null) {
break;
}
double number1 = Double.parseDouble(number1AsString);
double number2 = Double.parseDouble(number2AsString);
double result = number1 * number2;
System.out.println("result:" + result);
output.println(result);
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
output.close();
file1.close();
file2.close();
}
}
Edit: Also you may want to modularize your code for instance creating a method that help reduce duplicated code. Also you may be interested to look for NumberFormatException in case any number is not properly formatted or includes letters for example.
private double readDoubleFromFile(BufferedReader file) throws IOException {
String numberAsString = file.readLine();
if (numberAsString == null) {
throw new IOException();
}
double number = Double.parseDouble(numberAsString);
return number;
}
The DataInputStream class is not for reading text files. it can only be used to read what DataOutput writes. If you have rows of human-readable numbers, you need to use an InputStreamReader and then parse the resulting streams with things like Double.parseDouble
Maybe you want to use a BufferedReader for this.
BufferedReader in = new BufferedReader(
new FileReader(args[0]));
Then:
String num = null;
while((num = in.readLine()) != null){
double d = Double.parseDouble(num);
//now you have a double value
}
This way you do not depend on the exception to indicate the end of file.
You need to call output.flush just before closing the stream. Also, you should close the streams to the files in a finally block, this will make sure that the close command wil always be executed.
The DataInputStream class reads from a binary file (or other source such as socket). This means that it is going to be completely misinterpreting those input text files, with possibly amusing (or very irritating) results. To read numbers from a text file, you should use a BufferedReader wrapping an InputStreamReader to read lines and then convert those to numbers with suitable parsing methods (e.g., Double.parseDouble if you're wanting to produce a floating-point number).
When testing these things, it's often helpful to put in some debugging output inside the loop that prints out each value as you read it. Like that, you can see if things have got stuck in some unexpected way.
With this while (true) without a break your code is basically running in an infinite loop and never stopping unless there's an exception.
If it did terminate but you didn't see an exception, then it might be caused by calling System.exit(1) in the catch. It might be too late then to print "Error" anyway (the stdout might have been abrupted too early) and the file will never be flushed/closed. Remove that System.exit(1) line.
Also, closing is supposed to happen in finally block. And best is to not print some nothing-saying message on exception but just let them go. Since you already have a throws Exception on the method, just remove the entire catch. Only use it when you can handle exceptions in a sensible manner.
PrintWriter output = new PrintWriter("output2.txt");
try {
output.println("something");
} finally {
output.close();
}
After
output.println(result);
add
output.flush();

Categories