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"));
Related
So we got this assignment in a basic java programming course and we're supposed to implement a kind of card deck. To help us with this they have given us resources that will present a GUI on the screen, but when running my program I get a IOException that says that it can't read the input file, most likely since the pathname is wrong. And I dont know how to fix it, we're not even supposed to be in meddling with this code. The error is thrown in this method:
private Image getImg(Card aCard) {
File pathToFile = null;
if (aCard == null) {
pathToFile = new File("cardset-oxymoron/shade.gif");
} else {
String suits = "cdhs";
char c = suits.charAt(aCard.getSuit());
String fileName = String.format("%s/%02d%c.gif", "cardset-oxymoron", aCard.getRank(), c);
pathToFile = new File(fileName);
}
Image img = null;
try {
img = ImageIO.read(pathToFile);
} catch (IOException ex) {
System.err.println("Failed to create image");
ex.printStackTrace();
}
return img;
}
And according to the error stack(?) it is at line 99, which is the
img = ImageIO.read(pathToFile);
line
The folder that the cards are in is inside the project folder, right in between bin and src. using IntelliJ debugger I can see that the the pathToFile is "cardset-oxymoron\02d.gif". The filename is correct as all the cards are "[01-13][c/d/h/s].gif". When I rightclicked and copied the path to the files inside IntelliJ it was using forwardsslashes and not backslashes. But then I checked in explorer and it was the other way around... I have no idea where this is going wrong, any input would be greatly appreciated!
According to your code your files are in directory cardset-oxymoron relative to your JVM run directory. I'm not sure about IntelliJ (I work all the time with Eclipse and Maven), but it could be bin directory.
You can check it by put those 2 lines to see what is it actually (somewhere before your actual code)
File currentDir = new File("./");
System.out.println(currentDir.getAbsolutePath());
Then your cardset-oxymoron must be in that directory. Or you can change file path appropriately.
E.g. if currentDir is bin then pathToFile will be
pathToFile = new File("../cardset-oxymoron/shade.gif");
as well as fileName for other case.
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'.
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
I'm very new at coding java and I'm having a lot of difficulty.
I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt".
So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.
I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file.
It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".
This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
There are two main options available
Use absolute path to file (begins from drive letter in Windows or
slash in *.nix). It is very convenient for "just for test" tasks.
Sample
Windows - D:/someFolder/scores.txt,
*.nix - /someFolder/scores.txt
Put file to project root directory, in such case it will be visible
to class loader.
Place the scores.txt in the root of your project folder, or put the full path to the file in String file.
The program won't know to check your My Documents folder for scores.txt
If you are using IntelliJ, create an input.txt file in your package and right click the input.txt file and click copy path. You can now use that path as an input parameter.
Example:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
Take the absolute path from the local system if you'r in eclipse then right-click on the file and click on properties you will get the path copy it and put as below this worked for me In maven project keep the properties file in src/main/resources `
private static Properties properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`
I am new for Importing file using scanner line by line reader .When i have import file it's working correctly , but some other system(i.e. colleague system) same project and same database connection while importing file error like Java.io.FileNotfoundException local drive fake path directory (e.g: "c:\fake path\db.sql").
public boolean checkfile(String dbfile){
File obj = new File(dbfile)
Scanner scr = new Scanner(obj );
try{
while(scr .hasNext()){
String scr_line = scr.nextLine();
System.out.println(scr_line );
}
}catch(Exception ex){
System.out.println(ex.tostring());
}
}
Above code File obj = new File(dbFile) this line error message showing like Java.io.FileNotFoundException local drive fake path directory . can any please help me where i have done mistake above this code .
1 , File you try read is not available in your colleague system or where you run this java program
2 , check this file "c:\fake path\db.sql" is available or not in where you run this java program
3 , When you run the program make sure you are sending the file path based on the Environment(Windows,unix etc.....)
4 , check File availability first
try
{
File f = new File("c:\fake path\db.sql");
if(f.exists())
{
//read the file
}
}
catch(Exception e)
{
// do some work
}