I am creating a program where two numbers are read from one file (test.in) and then the sum is output to another file (test.out). I created the two files as TXT documents in the bin folder of my project but it still gives this
Exception in thread "main" java.io.FileNotFoundException: test.in.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at test.main(test.java:11)
The files are not showing up in my project directory on the left hand side of the screen, it just won't work.
import java.io.*;
import java.util.*;
public class test {
public static void main (String [] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("test.in.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out.txt")));
StringTokenizer st = new StringTokenizer(f.readLine());
int i1 = Integer.parseInt(st.nextToken()); // first integer
int i2 = Integer.parseInt(st.nextToken()); // second integer
out.println(i1+i2); // output result
out.close(); // close the output file
}
}
As you can see your file is an textdocument, so it ends with ".txt" even if you can't see it in the folder!
You have to change "test.in" and "test.out" into "test.in.txt" and "test.out.txt"
import java.io.*;
import java.util.*;
public class test {
public static void main (String [] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("test.in.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out.txt")));
StringTokenizer st = new StringTokenizer(f.readLine());
int i1 = Integer.parseInt(st.nextToken()); // first integer
int i2 = Integer.parseInt(st.nextToken()); // second integer
out.println(i1+i2); // output result
out.close(); // close the output file
}
}
If your files are ".txt" your strings "test.in" and "test.out" need to be renamed.
The other option is to change "test.in.txt" to "test.in" and
"test.out.txt" to "test.out".
Your files have to be from type "IN" and "OUT" not "TXT". As your screenshot shows they are not.
The fact that you are not seeing the suffix "txt" may be depending on your settings on your OS.
Your files also have to be in the same directory as your test.java file.
You should check your path and the filename. If "test.in" file is not in the folder that you invoked "java" command, it is normal to get this exception.
Putting your files in the bin of the project is not the solution. The files are supposed to be in the root directory of your project. There might be some other issues like the name of your files; try to reference the files by their absolute path. E.g. BufferedReader f = new BufferedReader(new FileReader("C:/MyProjetFolder/bin/test.in"));.
If that doesn't work then the issue could be the extensions of the files. So check the metadata of your files to see if the extensions are as expected. If it's not, then rename the files to the extensions in the metadata (properties).
You dont have to put the files in the bin folder. Put them in your project folder, the parent of bin/ and it will work.
I know this is a long time after I posted the question but I stumbled upon it and discovered that the real reason that it did not work is because the "f" input reader is never closed while the "out" output reader is closed. I simply had to add "f.close();" in order to make it work. It had nothing to do with the names of the text files, lol.
Here is the working code.
import java.io.*;
import java.util.*;
public class test {
public static void main (String [] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("test.in.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out.txt")));
StringTokenizer st = new StringTokenizer(f.readLine());
int i1 = Integer.parseInt(st.nextToken()); // first integer
int i2 = Integer.parseInt(st.nextToken()); // second integer
out.println(i1+i2); // output rresult
f.close();
out.close();
// close the output file
}
}
Related
I'm trying check and see if my program is scanning in the contents of a File however get this error:
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at lottery.main(lottery.java:40)
I don't see the problem as in my code as I always do my files this way, can't seem to understand to the problem.
Code:
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the file with the ticket data.");
String input = in.nextLine();
File file = new File(input);
in.close();
Scanner scan = new Scanner(new FileInputStream(file));
int lim = scan.nextInt();
for(int i = 0; i < lim * 2; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
System.out.println("Name " + name);
}
scan.close();
}
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. From docs.oracle.com
This means your FileInputStream wants an actual file system file provided. But you only made a filehandler when calling new File(). so you need to create the file on the file system calling file.createNewFile();
File file = new File(input); //here you make a filehandler - not a filesystem file.
if(!file.exists()) {
file.createNewFile(); // create your file on the file system
}
Scanner scan = new Scanner(new FileInputStream(file)); // read from file system.
Check if you start the jvm from the directory where the input file is located.
If not there is not possibility to find it with a relative path. Eventually change it to an absolute path (something like /usr/me/input.txt).
If the file is located on the directory where you start the java program check for the rights of the file. It could be not visible for the user launching the java program.
The problem is that your program could not find input.txt in the current working directory.
Look in the directory where is your program running and check it has a file called input.txt in it.
I am a beginner Java student, working on our first class assignment.
In this assignment, I need to read a txt file, and fill an array with its contents, first space in the array per line.
My professor gave us code to do this, but I keep getting an error that the file cannot be read each time I try.
I am using Netbeans 8, on a Mac, and the file States.Fall2014.txt is located in the src folder, with all of my java classes.
Exception in thread "main" java.io.FileNotFoundException: States.Fall2014.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at main.main(main.java:21)
Java Result: 1
Here is the code I have. I have only included the code that pertains to opening the file, as I'm sure you have no wish to be spammed with the other classes.
The commented code during the trimming is to echo print, to make sure the file is being read in properly (not currently needed since the file isn't being read in at all).
import java.io.*;
public class main {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
StateCollection Sdriver = new StateCollection(50);
//Sdriver = new StateCollection(50);
//Creates object of collection class
FileReader fr= new FileReader("States.Fall2014.txt");
BufferedReader br1 = new BufferedReader (fr);
String inputString;
String stateName;
String stateCapital;
String stateAbbrev;
int statePop;
String stateRegion;
int stateRegionNum;
inputString = br1.readLine();
while (inputString != null)
{
stateName = inputString.substring(1, 15).trim();
//System.out.println("stateName read in was: " + stateName);
stateCapital = inputString.substring(16, 30).trim();
//System.out.println(“stateCapital read in was: “ + stateCapital);
stateAbbrev = inputString.substring(31, 32).trim();
//System.out.println(“stateAbbrev read in was: “ + stateAbbrev);
statePop = Integer.parseInt(inputString.substring(33, 40));
//System.out.println(“statePop read in was: “ + statePop);
stateRegion = inputString.substring(41, 55).trim();
//System.out.println(“stateRegion read in was: “ + stateRegion);
stateRegionNum = Integer.parseInt(inputString.substring(56));
//System.out.println(“stateRegionNum read in was: “ + stateRegionNum);
//Code to create object
inputString = br1.readLine(); // read next input line.
}
br1.close(); //Close input file being read
Change
FileReader fr= new FileReader("States.Fall2014.txt");
to
FileReader fr= new FileReader("src/States.Fall2014.txt");
or move the file up one level to the project directory.
Make sure that the TXT file is in the right folder/area.
You shouldn't have it with your class, as the other answer states, you need it in the root folder.
Move the file up one level, to the same as the src folder.
The src directory is not (necessarily) the directory the .class file is in. Make sure States.Fall2014.txt is on the class-path.
This one's a fun one. I'd appreciate any bit of help, and no previous stackoverflow questions are pointing me in the right location. Docs also weren't very helpful to me.
I'm being thrown a FileNotFoundException with this block of code:
public static int wordOccurance(Word t, File D) throws FileNotFoundException
{
int occurance = 0;
BufferedReader mainReader = new BufferedReader(new FileReader(D));
Scanner kb = new Scanner(mainReader);
My tester file does not cause this to occur: ie. "File tester = new File("C:\read.txt");"
But the problem occurs solely when I pass a File constructed by this method:
public static File makeAndCombineFile(String FileOne, String FileTwo) throws IOException
{
BufferedReader mainReader = null;// null holder value for the later useful bufferedReader
Scanner kb = null;// null holder for later useful Scanner
StringBuilder sb = new StringBuilder();
OTHER CONDITIONS BETWEEN THESE TWO CHUNKS. MOST LIKELY NOT PERTINENT. ALSO RETURN FILE, JUST IF ONE INPUT IS NULL.
else //in case both are good to go and obviously not null
{
mainReader = new BufferedReader(new FileReader(FileOne));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine() + "\n");
mainReader = new BufferedReader(new FileReader(FileTwo));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine()+ "\n");
kb.close();
return new File(sb.toString());
}
}
It took me a while to figure out what was going on here, but it looks to me like you think that this line:
return new File(sb.toString());
creates a file on disk containing the text read from the two scanners. It does not. It creates a java.io.File, which is basically a representation of a file path; the path represented by this File is the data read from the scanners. In other words, if FileOne and FileTwo contained the text to War and Peace, then the path represented by that file would be the the text of War and Peace. The file will not have been created on disk; no data will have been written to it. You've just created an object that refers to a file that does not exist.
Use a FileWriter, perhaps in conjunction with a PrintWriter, to save the lines of text into a file; then you can create a File object containing the name of that file and pass it to your other routine:
PrintWriter pw = new PrintWriter(new FileWriter("somename.txt"));
while(kb.hasNext())
pw.println(kb.nextLine());
pw.close();
return new File("somename.txt");
My goal is to write a csv file to a specific location on my computer. The problem is that I keep getting the FileNotFoundException error when I compile my program. I know my where my problem is.
Its here,
FileWriter fw = new FileWriter("://Users/michaelrichards/NetBeansProjects/UniProject/src");
Can someone please tell me the format when typing out a path in terminal.
import java.io.*;
public class WriteToFile
{
public static void main(String[]args) throws IOException
{
FileWriter fw = new FileWriter("://Users/michaelrichards/NetBeansProjects/UniProject/src");
BufferedWriter bw = new BufferedWriter(fw);
String myArray[] = {"one", "two", "three"};
String writableString = "";
for(String item : myArray)
{
writableString += item + ",";
}
writableString = writableString.substring(0, writableString.length() - 1);
bw.write(writableString);
bw.close();
}
}
I am not a Mac user, but as far as I know, your path should be /Users/michealrichards/.... You could also use the Java system property user.home to get the home directory of the current user, independent of the platform:
String path = System.getProperty("user.home") + "/NetBeansProjects/UniProject/src";
Edit: I just noticed that you are trying to open a directory (src) as a file! This won't work anyway. You have to pass a path to a file to the FileWriter constructor.
OS X is a Unix based system so your path should be
/Users/michaelrichards/NetBeansProjects/UniProject/src
If you are using Windows use like D://Folder/folder/raghu.txt
in linux /home/(user name)/Desktop/raghu.txt
Java newbie here!
I'm writing a program to practice reading input and writing output to files. I've finished coding the program, but when I run it, the program just catches and proceeds with a FileNotFoundException.
The file is in the source folder for the program, and I've even tried placing it in every folder related to the program. I've tried:
Declaring the exceptions in the method header
Surrounding the section-in-question with a try/catch block.
Both of the above together.
Here's the relevant code that is causing problems. Is there something that sticks out that I'm missing?
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
String playerHighestScore = "", playerLowestScore = "";
int numPlayers = 0, scoreHighest = 0, scoreLowest = 0;
System.out.println("Enter an input file name: ");
String inputFileName = keyboard.nextLine();
String outputFileName = getOutputFileName(keyboard, inputFileName);
File inputFile = new File(inputFileName);
try {
Scanner reader = new Scanner(inputFile);
reader.close();
}
catch (FileNotFoundException exception) {
System.out.println("There was a problem reading from the file.");
System.exit(0);
}
Scanner reader = new Scanner(inputFile);
PrintWriter writer = new PrintWriter(outputFileName);
The answer is simple. If you get a FilENotFoundException, obviously the reason is File Not Found in the given path.
If you use an IDE, path for the working directory is different from the source directory.
For example, if you are using NetBeans, your source files are inside /src. But your working directory (.) is the project directory.
In the other hand, the problem may be the thing that #Don mentioned. If you are going for a cross platform approach, you can use "/" in paths. It works irrespective to the OS.
Example : String fileName = "C:/Directory/File.txt";
And these paths are case sensitive. So make sure you use the correct case. (It won't be a problem in Windows, until you package the program.)