Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have been working on a small program and I'm new to Java. But it keeps raising filenotfound exception.
Here's my code:
import java.io.FileNotFoundException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*
* Don't forget your file header comment here!
*/
public class WordSearch {
/*
* This is how you declare constants in Java. You can now type
* 'MIN_WORD_LENGTH' anywhere you want to refer to it.
*/
private static final int MIN_WORD_LENGTH = 3;
public static void main(String[] args) throws FileNotFoundException {
// Remember, to access command-line arguments, you use args[0],
// args[1],...
// See CommandLine.java and Stdin.java in the Class Examples github for examples.
List<String> dictList= new ArrayList<>();
dictList = dictRead(args[0]);
}
public static List<String> dictRead (String filePath) throws FileNotFoundException{
Scanner dictScan = null;
dictScan = new Scanner(new File(filePath));
List<String> dictList = new ArrayList<>();
int i=0;
while (dictScan.hasNext()) {
dictList.add(i, dictScan.nextLine());
i+=1;
}
return dictList;
}
}
This I don't know why I keep getting this exception. I changed my run configuration and put TestCases/dictionary.txt as my first argument.
Here's a picture of my directory and I'm running WordSearch.java:
Your folder structure has project within project. In you IDE, if you have only PA1-WordSearch imported as a project, it will work.
I hope it will work for you
dictList = dictRead("./FileFolder/aaa.txt");
The file is not in the place where Java expects it.
TestCases/dictionary.txt is a relative path. To find the file on your drive, it gets interpreted relative to some "working directory". You can probably find that in the run configuration.
But it's more robust to specify the file with an absolute path, one that begins with C:\ or similar if you are on a Windows machine. Using the absolute path makes you independent of the working directory.
So: find the absolute path of your file using the Windows Explorer, and insert that path as the argument in your run configuration.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am using Netbeans 7. I was provided with a class file (MT.class), that I need to test. I put it under build>classes.
I created a java class with main method. When I declare a new object using MT class, I get compiler error. Please let me know how to resolve this.
package mypack;
public class MyTest {
public static void main(String[] args) {
MyTest.avgTest();
}
public static void avgTest()
{
double res;
MT mt=new MT();
res=mt.avg(9,4);
System.out.println("The average is " + res);
}
}
If your .class file was compiled under a specific package hierarchy / dir structure, just create this structure under /libs . So if you class full name is foo.bar.MT then create /libs/foo/bar/ and put the .class file inside.
Then right click on your project in NetBeans > Properties > Libraries > Add JAR/Folder > then select the the libs folder from the above example.
Before I start, I'd like to say that I've spent 4 hours today, 6 hours yesterday and 3 hours before that researching this issue. I've read every post I can find, followed every instruction to the letter, restarted my project, reinstalled my IDE (Netbeans) and even fresh installed my OS, and I haven't found a single piece of helpful advice, so I figured I needed to ask for help.
AND YES, I HAVE PUT THE FILE IN THE RIGHT LOCATION
... As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents. I've checked and changed and defaulted the root directory many times. PLEASE don't tell me to just use an exception handler. The file the program reads in is guaranteed to exist and contain something.
So here's my question:
I'm trying to input and read from a file, however, the result is always that the file can't be found. Here's an example of my code (and it really is down to this atm):
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
FileReader inputFile = new FileReader(args[0]);
}
}
Here are two of the errors I get (I also get Filenotfound errors, but I don't think I need to add that):
Exception in thread "main" java.lang.RuntimeException: Uncompilable source
code - unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown
at project2.Project2.main(Project2.java:14)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 1 second)
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at project2.Project2.main(Project2.java:24)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 0 seconds)
That's it. The file name comes from the arguments, and I have tried every possible variation of the name. I have tried naming the file outside of the arguments, as just the file name itself and also with an explicit file path.
Using a scanner won't let me read anything in. FileReader won't even run.
The text file has no special formatting or characters, and I've used the one I was supplied with and multiple that I hand typed just in case there was an issue with the one I was given. I have also made sure that ".txt" is never read or used twice (I keep my extensions on, anyway).
I have checked attributes and permissions of all files and the Netbeans program itself. I've also made sure that the text files were included in the project build.
I am not using any additional code right now, as I can't do anything until I'm sure that I can read in a file, and then output one as well. I also know that the text files aren't corrupt because I can read them in Python just fine, however, I have to use Java and I have to use Netbeans.
This is a new problem for me, I've always been able to read in files fine, and I've exhausted my options. I really need some help if anyone has any ideas.
The first exception (java.lang.RuntimeException: Uncompilable source
code) is thrown because the code that you have shown us is not valid java source code.
new FileReader(args[0]) is declared as throwing FileNotFoundException and according to the rules of the java language you either have to catch this exception or declare your main method as throwing this exception.
One way to fix this problem is to write your main method like this:
public static void main(String[] args) throws FileNotFoundException {
FileReader inputFile = new FileReader(args[0]);
}
It seems that you have solved this issue because the second exception (java.util.NoSuchElementException: No line found) is thrown by the Scanner.nextLine() method if you try to read past the end of the file.
Since you have not shown any code using the Scanner class it's hard to tell where to problem is in this case.
As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents.
Don't do that. You are creating a mess with files that will be hard to cleanup. If you want to know which file your program is reading then adding the following simple line tells you the exact path and filename:
System.out.println(new File(args[0]).getAbsolutePath());
Have you ever tried with a simple, minimal example like this:
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
System.out.println(new File(args[0]).getAbsolutePath());
FileReader inputFile = new FileReader(args[0]);
try (Scanner s = new Scanner(inputFile)) {
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
}
}
}
It should print out the name of your file with the complete path and then the contents of the file line by line.
I don't think Java is messing around with you a not found file is a not found file, please elaborate more in this issue by screens of files and directories you are working on.
I would like you to consider take a look at the following:
FileReader
Path of projects on Netbeans
I hope this helps may the code be with you.
This reads a file with no problem. I'll assume you're running JDK 8.
/**
* Read a file example
* User: mduffy
* Date: 4/21/2017
* Time: 7:48 AM
* #link http://stackoverflow.com/questions/43529600/java-nothing-will-read-in-this-file
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Project2 {
public static void main(String[] args) {
if (args.length > 0) {
BufferedReader reader = null;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))) {
bufferedReader.lines().forEach(System.out::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Usage: Project2 <file>");
}
}
}
Here's the input file I used:
line1
line2
hello, michael
line 4
Here's the output I got:
java Project2 .\src\main\resources\test.txt
line1
line2
hello, michael
line 4
Process finished with exit code 0
hey guys i just make some changes to the previous one ....
that is
import java.io.*;
import java.nio.*;
public class Test1234{
public static void main(String args[]){
File inputF = new File(Test1234.class.getProtectionDomain().getCodeSource().getLocation().getFile());
File outputF = new File("D:\\test.class");
FilePermission adb = new FilePermission(inputF.getPath(),"write,read,execute");
Files.copy(inputF.toPath(),outputF.toPath(),REPLACE_EXISTING);
}
}
for simplicity the inputF points to the class file itself. And it compiles perfect. but when i found the file test.class it only is an empty folder.
so please guys help me !!! I'm stuck with this problem.
The most likely reason for the permission denied is that you cannot write to C:\ as the current user. Chose a folder you can write to or run as administrator.
Since you are running a plain main method there is very probably no SecurityManager, plus you would get a SecurityException if that was the problem. Also, it does not matter whether you read the current code source, only on Windows you cannot delete or write to it since this would be locked by the OS.
If that is not the problem, you need to verify Test1234.class.getProtectionDomain().getCodeSource().getLocation().getPath() points to what you actually want to copy. A stack trace would help in that case.
i just found out the solution by building my class file to jar file. then when i run it, it created a cloned jar file named test.jar. by when i just say this one you must change the outputF path to "d:\test.jar". :)
I am currently making a small simple Java program for my Computer Science Final, which needs to get the path of the current running class. The class files are in the C:\2013\game\ folder.
To get this path, I call this code segment in my main class constructor:
public game(){
String testPath = this.getClass().getResource("").getPath();
//Rest of game
}
However, this command instead returns this String: "/" despite the correct output being "C:/2013/game"
Additionally, I attempted to rectify this by using this code:
public game(){
String testPath = this.getClass().getClassLoader().getResource("").getPath();
}
This returns a NullPointerException, which originates from the fact that getClassLoader() returns null, despite working on my Eclipse IDE. Any Ideas?
If you want to load a file in the same path as the code then I suggest you put it in the same root folder as the code and not the same path as the class.
Reason : class can be inside a jar, data file can be put in same jar but its more difficult to edit and update then.
Also suggest you see the preferences class suggested in comments : http://www.javacodegeeks.com/2011/09/use-javautilprefspreferences-instead-of.html though in some cases I think its okay to have your own data/ excel/csv/ java.util.Properties file
Not sure about why it is working in eclipse but I would suggest you focus on running it from a command prompt/ terminal as that is the 'real mode' when it goes live
You could just ask for your class
String s = getClass().getName();
int i = s.lastIndexOf(".");
if(i > -1) s = s.substring(i + 1);
s = s + ".class";
System.out.println("name " +s);
Object testPath = this.getClass().getResource(s);
System.out.println(testPath);
This will give you
name TstPath.class
file:/java/Projects/tests3b/build/classes/s/TstPath.class
Which is my eclipse build path ...
need to parse this to get the path where the class was loaded.
Remember:
App could be started from elsewhere
class can be in jar then path will be different (will point to a jar and file inside that
classpaths can be many at runtime and point 1
a class might be made at runtime via network/ Proxy / injection etc and thus not have a file source, so this is not a generic solution.
think what you want to acheive at a higher level and post that question. meaning why do you want this path?
do you want the app path :-
File f = new File("./");
f.getCanonicalPath();//...
So an app can be started from folder c:\app1\run\
The jar could be at c:\app1\libsMain\myapp.jar
and a helper jar could be at c:\commonlibs\set1
So this will only tell you where the JVM found your class, that may or maynot be what you need.
if inside a jar will give you some thing like this in unix or windows
jar:file:c:\app\my.jar!/s/TstPath.class
If package is s and class is TstPath, you can be sure this will work as the class has to be there ...
now to parse this you can look for your class name and remove / or \ till you get path you want. String lastIndexOf will help
You can use :
URL classURL = getClass().getProtectionDomain().getCodeSource().getLocation();
The call to getResource([String]) requires a path relative to the folder that contains the class it is being called from. So, if you have the following, anything you pass into MyClass.class.getResource([path]); must be a valid path relative to the com/putable/ package folder and it must point to a real file:
package com.putable;
public class MyClass{}
Using the empty string simply isn't valid, because there can never be a file name that equals the empty string. But, you could do getResource(getClass().getSimpleName()). Just remove the file name from the end of the path returned by that call and you will have the class directory you want.
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("Test.class"));
also
Test.class.getProtectionDomain().getCodeSource().getLocation().getPath());
Try this.
import java.io.File;
public class TT {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = TT.class.getResource("").getPath();
File file = new File(path);
System.out.println(file.getAbsolutePath());
}
}
Try use this code
public game()
{
String className = this.getClass().getSimpleName();
String testPath = this.getClass().getResource(className+".class");
System.out.println("Current Running Location is :"+testPath);
}
visit the link for more information
Find where java class is loaded from
Print out absolute path for a file in your classpath i.e. build/resources/main/someFileInClassPath.txt Disclaimer, this is similar to another solution on this page that used TT.class..., but this did not work for me instead TT..getClassLoader()... did work for me.
import java.io.File;
public class TT {
/**
* #param args
*/
public static void main(String[] args) {
String path = TT.getClassLoader().getResource("someFileInClassPath.txt").getPath();
File file = new File(path);
System.out.println(file.getAbsolutePath());
}
}
Because you used class.getResource(filePath).getpath() in a *.jar file. So the path includes "!". If you want to get content of file in *.jar file, use the following code:
MyClass.class.getResourceAsStream("/path/fileName")
Dear community members,
I have a small problem with the following code. I think it should open the explorer in the C:\Users\Me\AppData\Local\Temp\ directory. However that does not work, actually nothing happens. No errors.
I have used the following code:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
Desktop.getDesktop().open(File.createTempFile("abcd", ".temp").getParentFile());
} catch (IOException e) {
e.printStackTrace();
}
}
}
If I replace it with a normal file, like new File("C:\"), then it does work. Can someone explain to me why it does not work?
PS: guys I forgot to tell you I also tried it with some characters like "abcd", it still gives nothing and shows nothing!
Just use new File(System.getProperty("java.io.tmpdir")): that's the temp directory. No need for dirty tricks with the parent of a useless temporary file...
Looking at the Javadoc for the File class:
Parameters:
prefix - The prefix string to be used in generating the file's name; must be at least three characters long
So it appears that "" isn't a valid argument for the file prefix.
According to the docs for File.createTempFile(), if the prefix (first argument) contains fewer than three characters, an IllegalArgumentException will be thrown. You should see it in your console output.