It has been a long time since I messed with files. I am trying to take a txt file I make in eclipse and use it in this code. The code to handle getting file name, finding file, and scanning it is:
System.out.println("Input from a file");
System.out.print("Enter file name: ");
String str = expression.nextLine();
int i = 0;
File file = new File(str);
Scanner fScan = new Scanner(file);
All I get are FileNotFoundExceptions. My file is in the same exact folder that all my classes for this program are in. I can't find an actual helpful answer online either .
So if someone could point out where I am going wrong that would be great :)
all of these lines of code you are having should be inside a try{} and outside have a catch, that would catch the fileNotFoundException, for example,
Try{
/*your code here*/
// but try this
Scanner scannerName = new Scanner("FileName.<extension>"); //extension being .txt, etc
String str;
while(scannerName.hasNext());{
str = scannerName.nextLine();
/*work with str here*/
}
Catch(FileNotFoundException e){
System.out.println("File not found");
}
Are you sure that the file is in the root folder ? The default working directory, is the project directory.
If you are sure that your file is there then it's either your mistaken when typing the name of your file, or somethine else is happening, to figure it out, I suggest you to try the following 3 tests :
1-make sure when you type the name of the file there is no mistake
2-Try to put the full path of the file and see if now it will find it
3-Try to put as name something like
new File("src/pa/Yourinput.txt").
If you have the file in the same package where is the class file then you can try this one also:
Scanner fScan = new Scanner(this.getClass().getResourceAsStream("abc.txt"));
//do not forget to close the Scanner in the end
fScan.close()
OR
Looking a file abc.txt from resources folder
File file = new File("resources/abc.txt");
Here is the project structure
Related
I'm trying to create a new text file in java by having the user input their desired file name. However, when I look in the directory for the file after I run the code once, it doesn't show up.
import java.util.Scanner;
import java.io.File;
public class TestFile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
}
}
Although, when I don't have the user input a file name and just have the code written with the name in quotation marks, the file ends up being created when I look back in the directory.
File file = new File("TestFile.txt")
Why won't it create a file when I try to use the String input from the user?
You must be mistaken because just calling new File(String) won't create a file. It will just create an instance of File class.
You need to call file.createNewFile().
Adding this at the end creates the file:-
if (file.createNewFile()) {
System.out.println("File created.");
} else {
System.out.println("File already exists.");
}
The following code worked for me:
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
boolean isFileCreated = file.createNewFile(); // New change
System.out.print("Was the file created? -- ");
System.out.println(isFileCreated);
The only change made to your code is to call createNewFile method. This worked fine in all cases. Hope this helps.
From the API:
Atomically creates a new, empty file named by this abstract pathname
if and only if a file with this name does not yet exist. The check for
the existence of the file and the creation of the file if it does not
exist are a single operation that is atomic with respect to all other
filesystem activities that might affect the file. Note: this method
should not be used for file-locking, as the resulting protocol cannot
be made to work reliably. The FileLock facility should be used
instead.
Please use below code to solve your issue. You just have to call createNewFile() method it will create file in your project location. You can also provide the location where you want to create file otherwise it will create file at your project location to create file at specified location you have to provide location of your system like below
String fileLocation="fileLocation"+fileName;
File file = new File(fileLocation);
import java.util.Scanner;
import java.io.File;
public class TestFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
file.createNewFile();
}
}
When faced with issues like this, it's really, really, really important to go hit the JavaDocs, because 90% of the time, it's just a misunderstanding of how the APIs work.
File is described as:
An abstract representation of file and directory pathnames.
This means that creating an instance of File does not create a file nor does the file have to exist, it's just away of describing a virtual concept of a file.
Further reading of the docs would have lead you to File#createNewFile which is described as doing:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
When you initialize your File file = new File("TestFile.txt"), it is not created yet.
You should write something to your file using FileWriter or others.
File f = new File(fileName);
FileWriter w = new FileWriter(f);
w.write("aaa");
w.flush();
or using f.createNewFile() as suggested in other answer.
Then you can see your file and its content.
Im trying to write a function that will take a string, then open a file with that string name and read the text. I know how to do this, but im having trouble with the fact that my text files are not saved in the same place as my java file.
It looks like this.
Project name/src/program.java
Project name/resources/text.txt
Im using the File class, but dont know what to put in the File constructor to open to the right place.
ie. File store = new File(xxxxxxxxxtext.txt)
Help me out with what goes in front of the file name please. Also, this is java 6 and im on windows 8.
This is my code:
public static void areaSearch(String a) {
Scanner reader = null;
try {
reader = new Scanner(new File("../resources/" + a+ ".txt"));
}
catch (Exception e) {
System.out.println("File: " + a +" not opended...");
}
Use relative path if it's on an easy relative path from your project folder:
File file = File("../resources/text.txt");
Or use absolute path:
File file = File("C:\\abcfolder\\text.txt");
Read documentation. There are more, than 1 constructor for File class. Use:
public File(File parent, String child)
I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.
so the problem is that I am having exception thrown each time I try to load the code below on NetBeans or Eclips, but when I try to run it thru TextMate everything works fine!
I tried to put the absolute address, changed the text file etc.. didn't help!
Can someone help me or tell why it won't run with IDE?
Thanks
void loadFile() {
try {
list = new LinkedList<Patient>();
FileReader read = new FileReader("a.txt");
Scanner scan = new Scanner(read);
while (scan.hasNextLine()) {
String Line = scan.nextLine();
String[] subArray = new String[5];
subArray = Line.split(",");
int a = Integer.parseInt(subArray[4]);
list.add(new Patient(Integer.parseInt(subArray[0]), subArray[1], subArray[2], subArray[3], a));
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
cap = list.size();
search_names = new int[cap];
for (int i = 0; i < list.size(); i++) {
search_names[i] = i;
}
setNames(search_names);
}//end loadFile
Debug log:
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsfd.jar
Have no file for /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Resources/Java/JavaRuntimeSupport.jar
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/sunrsasign.jar
}
In netbeans the default working directory is always the root folder, i mean the folder which contains the folders which name "src", "build" etc. Place the file along with these folders and it will do the trick.
Here is step by Step procedure in NetBeans IDE 7.0.1
Click on File menu.
Click on Project Properties.
In the categories, select Run.
In main class you select your current java file.
In Arguments select the file you want to read for e.g. abc.txt or abc.java
And in Working Directory write down the path of folder in which this abc.txt or abc.java lies.
Click OK to close Project Properties.
While running your program don't forget to select your project as Main Project.
Then click F^ on keyboard. i.e. You have to raun your main project instead of just running your current java file.
That's it....enjoy!!!!
Finally found the solution
In eclipse you should put the target file in project folder. Guess same applies to NetBeans.
I had my target file in "src" folder (where the actual code files were). In fact i had to just change it to upper folder where the project folder is.
Easy and simple.
Probably you have different "working directories" in you different setups. You can check which directory you are in by printing it like this:
System.out.println(new File(".").getAbsoluteFile());
In eclipse you can set set up the working directory in the run configurations, arguments tab.
Try BufferedReader?
EDIT: Edited to show example more closely to your code. I got excepption when using File Reader. But was able to .println with BufferedReader. I did not use Scanner.
EDIT2: I was also able to get your code to work. With Scanner etc(When using full path) (Example: FileReader read = new FileReader(""C:\\myfolder\\folder\\a.txt". So hmmm.
try {
list = new LinkedList<Patient>();
BufferedReader scan = new BufferedReader(new FileReader("C:\\a.txt"));
String lines;
try {
// Scanner scan = new Scanner(read);
while ((lines = scan.readLine()) != null) {
//I just printed lines you will do your stuff here
System.out.println(lines);
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
right click on your text file select properties and copy the path and paste it in the place where you have entered your file name
lets say you wanna add test.txt in netbeans
if your project in C:\myProject put the text file inside C:\myProject file directly not in the C:\myProject\src . then use:
File file = new File("test.txt");
Scanner in = new Scanner(file);
OR
Scanner input = new Scanner(new File("test.txt"));
This is my code to read a text file. When I run this code, the output keeps saying "File not found.", which is the message of FileNotFoundException. I'm not sure what is the problem in this code.
Apparently this is part of the java. For the whole java file, it requires the user to input something and will create a text file using the input as a name.
After that the user should enter the name of the text file created before again (assume the user enters correctly) and then the program should read the text file.
I have done other parts of my program correctly, but the problem is when i enter the name again, it just can not find the text file, eventhough they are in the same folder.
public static ArrayList<DogShop> readFile()
{
try
{ // The name of the file which we will read from
String filename = "a.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
ArrayList<DogShop> shops = new ArrayList<DogShop>();
// Read each line until end of file is reached
while (in.hasNextLine())
{
// Read an entire line, which contains all the details for 1 account
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
// 1st part is the account number
try
{ int shopNumber = lineBreaker.nextInt();
// 2nd part is the full name of the owner of the account
String owner = lineBreaker.next();
// 3rd part is the amount of money, but this includes the dollar sign
String equityWithDollarSign = lineBreaker.next();
int total = lineBreaker.nextInt();
// Get rid of the dollar sign;
// we use the subtring method from the String class (see the Java API),
// which returns a new string with the first 'n' characters chopped off,
// where 'n' is the parameter that you give it
String equityWithoutDollarSign = equityWithDollarSign.substring(1);
// Convert this balance into a double, we need this because the deposit method
// in the Account class needs a double, not a String
double equity = Double.parseDouble(equityWithoutDollarSign);
// Create an Account belonging to the owner we found in the file
DogShop s = new DogShop(owner);
// Put money into the account according to the amount of money we found in the file
s.getMoney(equity);
s.getDogs(total);
// Put the Account into the ArrayList
shops.add(s);
}
catch (InputMismatchException e)
{
System.out.println("File not found1.");
}
catch (NoSuchElementException e)
{
System.out.println("File not found2");
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
} // Make an ArrayList to store all the accounts we will make
// Return the ArrayList containing all the accounts we made
return shops;
}
If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)
If not, you should specify the absolute path to that file.
Edit:
You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.
If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.
Well.. Apparently the file does not exist or cannot be found. Try using a full path. You're probably reading from the wrong directory when you don't specify the path, unless a.txt is in your current working directory.
I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath
If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.
This is according to Core Java Volume I, section 3.7.3.
If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use
Scanner in = new Scanner(Paths.get("myfile.txt"));
But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.
This should help you..:
import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
find(Recipe);
}
public void find(String Name){
String newRecipe= Name+".txt";
try{
FileReader fr= new FileReader(newRecipe);
BufferedReader br= new BufferedReader(fr);
String str;
while ((str=br.readLine()) != null){
out.println(str + "\n");
}
br.close();
}catch (IOException e){
out.println("File Not Found!");
}
}
}
Just another thing... Instead of System.out.println("Error Message Here"), use System.err.println("Error Message Here"). This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()) in red.
NOTE: It also works when used with System.err.print("Error Message Here")