FileNotFoundException Java - java

I'm trying to make a simple highscore system for a minesweeper game. However i keep getting a file not found exception, and i've tried to use the full path for the file aswell.
package minesweeper;
import java.io.*;
import java.util.*;
public class Highscore{
public static void submitHighscore(String difficulty) throws IOException{
int easy = 99999;
int normal = 99999;
int hard = 99999;
//int newScore = (int) MinesweeperView.getTime();
int newScore = 10;
File f = new File("Highscores.dat");
if (!f.exists()){
f.createNewFile();
}
Scanner input = new Scanner(f);
PrintStream output = new PrintStream(f);
if (input.hasNextInt()){
easy = input.nextInt();
normal = input.nextInt();
hard = input.nextInt();
}
output.flush();
if(difficulty.equals("easy")){
if (easy > newScore){
easy = newScore;
}
}else if (difficulty.equals("normal")){
if (normal > newScore){
normal = newScore;
}
}else if (difficulty.equals("hard")){
if (hard > newScore){
hard = newScore;
}
}
output.println(easy);
output.println(normal);
output.println(hard);
}
//temporary main method used for debugging
public static void main(String[] args) throws IOException {
submitHighscore("easy");
}
}

You don't reveal on which line of code the exception is emitted. (Note: not posting all information you have about the problem reduces your chances of getting useful answers.)
However, my hunch is that it comes from the second call shown below, in which case the problem lies in trying to open the file twice:
Scanner input = new Scanner(f);
PrintStream output = new PrintStream(f);

Have you checked that the file exists and you have access rights for it?

Have you tried this?
if(f.isFile())
System.out.println("Yes, we have a file");
if(f.canWrite())
System.out.println("Yes, we have can write to the file");

Related

My java scanner doesn't seem to be reading my input (.txt file)

I am new to Java, and I am learning how to read input using Java on Eclipse. I am using a scanner to read a .txt input file, however, it doesn't seem to be reading the very first integer in the .txt file.
Here is the .txt file:
2 1 4
Here is my simplified code:
public class Test {
static int var;
static int[] arr;
public static void main(String[] args) {
String fileName = "/Users/anon/eclipse-workspace/Lab/src/input-01.txt";
readInput(fileName);
}
public static void readInput(String fileName) {
File file = new File(fileName);
Scanner fileInput = new Scanner(file);
//Read T
var = fileInput.nextInt();
System.out.printf("var: %d", var);
arr = new int[var];
}
I tried debugging, and I realized that "int var" never even appeared in the variables table on the right -- so I am not sure if "int var" was even initialized at all.
Please let me know if there are any other information that I can provide, and thank you in advance for you help and advices.
Check the input file contents. It could be a problem.
import java.io.File;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws Exception {
String fileName = "src/main/resources/input-01.txt";
readInput(fileName);
}
public static void readInput(String fileName) throws Exception {
File file = new File(fileName);
Scanner fileInput = new Scanner(file);
//Read T
int var = fileInput.nextInt();
System.out.println("var = " + var);
}
}
input-01.txt file content
10 sampletext
output
var = 10
Process finished with exit code 0

having issues with Java reading input files using netbeans

Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.

Input a text file through command line in java

I am trying to write a program that inputs a text file through the command line and then prints out the number of words in the text file. I've spent around 5 hours on this already. I'm taking an intro class using java.
Here is my code:
import java.util.*;
import java.io.*;
import java.nio.*;
public class WordCounter
{
private static Scanner input;
public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
openFile();
readRecords();
closeFile();
}
public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}
public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}
public static void closeFile()
{
if (input != null)
input.close();
}
}
Each way I've tried I get a different error and the most consistent one is "cannot find symbol" for the file argument in
input = new Scanner(new File(file));
I'm also still not entirely sure what the difference between java.io and java.nio is so I have tried using objects from both. I'm sure this is an obvious problem I just can't see it. I've read a lot of similar posts on here and that is where some of my code is from.
I've gotten the program to compile before but then it freezes in command prompt.
java.nio is the New and improved version of java.io. You can use either for this task. I tested the following code in the command line and it seems to work fine. The "cannot find symbol" error message is resolved in the try block. I think you were confusing the compiler by instantiating a File object named file twice. As #dammina answered, you do need to add the input.next(); to the while loop for the Scanner to proceed to the next word.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class WordCounter {
private static Scanner input;
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("File name not specified.");
System.exit(1);
}
try {
File file = new File(args[0]);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
int total = 0;
while (input.hasNext()) {
total += 1;
input.next();
}
System.out.printf("The total number of words without duplication is: %d", total);
input.close();
}
}
Your code is almost correct. Thing is in the while loop you have specified the terminating condition as follows,
while (input.hasNext()) // while there is more to read
However as you are just increment the count without moving to the next word the count just increases by always counting the first word. To make it work just add input.next() into the loop to move to next word in each iteration.
while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}

Getting FileNotFoundException when trying to run a java program through CMD using input and output files

When I try to run this code through eclipse, it works fine, but when I try to run it through CMD using "java MainClass >result.txt" I get a FileNotFoundException.
This is the code in question:
import java.io.;
import java.util.;
public class MainClass
{
static int cellNumber;
static int freeSpace;
static int randomResult;
static int chosen;
static int choiceSize;
public static void main(String[] args)
{
Scanner in = null;
try
{
in = new Scanner(new FileReader("C:\\users\\Alon\\workspace\\ex2temp\\bin\\input.txt"));
FileWriter fw = new FileWriter("C:\\users\\Alon\\workspace\\ex2temp\\bin\\result.txt");
PrintWriter pw = new PrintWriter(fw);
chosen = getRandomInt();
pw.printf("Choice=%d", chosen);
pw.println();
while (in.hasNext())
{
cellNumber = in.nextInt();
freeSpace = in.nextInt();
if (sizeOfChosen(chosen) <= freeSpace)
{
pw.printf("%d", cellNumber);
pw.println();
break;
}
}
if (!in.hasNext())
{
pw.println("Cannot allocate memory");
pw.println();
}
pw.close();
fw.close();
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Can anyone help please? Thanks :)
You're using the files from the ".../ext2temp/bin/.." which I assume it's Eclipse's output folder. Use the path where you have the original files.
In order to create a continuous writing on the same file, I had to append text into the existing file. I have added ", true" when creating the FileWriter. Then, I created a new BufferedWriter which received the FileWriter object, and finally, changed the PrintWriter receiving object to the bufferredWriter. This way, every time I run the program, 2 new lines of data are formed below the old ones and I get a "log file".

File not created by using File.createNewFile();

im having a small problem with my properties files with a PrintWriter.
This is the code for the main file:
package org.goverment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Tg {
public static final void main(String[] args) throws Exception {
cout("The Goverment - Create your own country!/");
cout("Press the number associated with your choice then press enter./");
cout("1. New Game/");
cout("2. Continue/");
cout("3. ExitGame/");
int c = Integer.parseInt(cin());
if(c == 1) {
cout("/");
cout("Country name: ");
String name = cin();
cout("\nIs this a soviet country? (y/n): ");
String soviet = cin();
boolean svt;
if(soviet.equalsIgnoreCase("y") || soviet.equalsIgnoreCase("yes"))
svt = true;
else if(soviet.equalsIgnoreCase("n") || soviet.equalsIgnoreCase("no"))
svt = false;
else
svt = false;
Game.setup(Game.cc(), name, svt);
} else if(c == 2)
System.exit(0); // Game.c();
else if(c == 3)
System.exit(0);
}
private static String cin() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
return br.readLine();
}
public static final void cout(String s) {
if(s.endsWith("/") || s.equalsIgnoreCase("")) {
System.out.println(s.substring(0, s.length() - 1));
} else {
System.out.print(s);
}
}
}
And this is the Game class:
http://pastebin.com/bktg6nSc
This is the problem:
The file isint created...
i keep flushing and closing but nothing happens.
i keep looking at the application data but no thegoverment.properties is there.
So what should i do?
I really do need help, its for a school project and i must do it by 2 days.
The bug is in Game.cc(). The method never returns if the for loop executes as written, so even though your code looks like it calls Game.setup(), the JVM never actually gets to execute it.
The problem is that regardless of the value of done when the while loop finishes, done is always reset to false before the while loop begins again. Classic infinite loop, and completely unrelated to your IO.
I had the following start to Game.cc() when I found the bug. Note the output lines added to aid in debugging.
public static final List<String> cc() {
List<String> countryNames = new ArrayList<String>();
System.out.println("About to begin for loop in Game.cc()");
for (int i = 0; i < 48; i++) {
System.out.println("for loop iteration "+i);
boolean done = false;
while (!done) {
You need to declare flag variables such as "boolean done = false;" outside the loop. Write future code like this:
public static final List<String> cc() {
List<String> countryNames = new ArrayList<String>();
boolean done = false;
for (int i = 0; i < 48; i++) {
while (!done) {
I should note that thegovernment.properties was correctly created after the fix, though not where one would expect to find it, since you hard-coded to Windows structures and I did not adjust the address before testing on linux. I found thegoverment.properties in the top--level folder of my package.
I should also note that after the properties file is created, it doesn't get modified ever again by Game.setup(), such as when the player starts a new game. Check your logic and test thoroughly to ensure that it's behaving the way you expect.
Best of luck in your studies!
If adding
writer.flush();
before closing does not work, then, intead of
PrintWriter writer = new PrintWriter(fl);
...
do
BufferedWriter writer = new BufferedWriter(fl);
writer.write("###################");
writer.newLine();
...
writer.flush();
writer.close();
If this still does not work try to create the file where you are executing the program, so:
File fl = new File("thegoverment.properties");

Categories