I need to read a .txt file of integers into a 2d array but when I try to read in the file I get a runetime error saying that the specified file cannot be found. This is the first time I've tried to read in a file so I just need direction on how to do it but I couldn't find an answer this basic.
I have the file of integers named "num1.txt" saved in the same folder as as my java file, so I'm wondering if I don't understand how eclipse and java decide where the file is.
public static void main(String[] args) throws FileNotFoundException
{
int i;
int j;
i=0;
j=0;
int connect4Array[][] = new int[6][7];
Scanner readFile = new Scanner(new File("num1.txt"));
while(readFile.hasNextInt())
{
for(i=0;i<connect4Array.length;i++)
{
connect4Array[i++][j]=readFile.nextInt();
for(j=0;j<connect4Array[j].length;j++)
{
connect4Array[i][j++]=readFile.nextInt();
}
}
}
First of all, it is NOT a compilation error. It is a runtime error. You need to learn the difference ... and to say the right thing, or else people won't understand what you are talking about.
I have the file of integers named "num1.txt" saved in the same folder as as my java file.
The problem is that you are trying to access the file in the running application's current directory ... but the current directory is not the place that you think / hope it is.
So where is the application's current directory? It depends on how you ran the application!
If you run the java app from a shell, then the current directory will default to the shell's current directory.
You can change it by cd-ing before you run java ... and I think you can also specify it using -Duser.dir=<pathname>.
If you run the java app from Eclipse, then the current directory will default to the project directory. That is probably different to the directory containing the source code.
You can specify a different current directory in the Eclipse settings for your application's launcher.
Alternatively, use an absolute path for the file, or put it into your application's JAR file and read it as a "resource".
move the file to where the src folder located.
because the default is project directory in your workspace.
you can use getProperty to check current directory.
String CurrentDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + CurrentDir);
Related
I'm trying to use a file in my code but I don't want to have specify the absolute file path, only the file name, for example "fileName.txt".
I want to do this so I have the ability to use this code on different laptops where the file may be stored in different folders.
The code below is what I'm using at the moment but I receive a NoSuchFileException when I ran it.
FileSystem fs FileSystems.getDefault();
Path fileIn = Paths.get("fileName.txt");
Any ideas how to overcome this problem so I can find the file without knowing its absolute path?
Ideas on how to find the file without knowing its absolute path:
Instruct the user of the app to place the file in the working directory.
Instruct the user of the app to give the path to the file as a program argument, then change the program to use the argument.
Have the program read a configuration file, found using options 1 or 2, then instruct the user of the app to give the path to the file in the configuration file.
Prompt the user for the file name.
(Not recommended) Scan the entire file system for the file, making sure there is only one file with the given name. Optional: If more than one file is found, prompt the user for which file to use.
if you don't ask the user for the complete path, and you don't have a specific folder that it must be in, then your only choice is to search for it.
Start with a rootmost path. Learn to use the File class. Then search all the children. This implementation only returned the first file found with that name.
public File findFile(File folder, String fileName) {
File fullPath = new File(folder,fileName);
if (fullPath.exists()) {
return fullPath;
}
for (File child : folder.listFiles()) {
if (child.isDirectory()) {
File possible = findFile(child,fileName);
if (possible!=null) {
return possible;
}
}
}
return null;
}
Then start this by calling either the root of the file system, or the configured rootmost path that you want to search
File userFile = findFile( new File("/"), fileName );
the best option, however, is to make the user input the entire path. There are nice file system browsing tools for most environments that will do this for the user.
I have a simple program in Intellij that I made just to test out reading file path of config file.
I created a simple test case where I would use a timer to print "Hello world" periodically in N intervals where N is in milliseconds and N is configurable.
This is the code:
public void schedule() throws Exception {
Properties props=new Properties();
String path ="./config.properties";
FileInputStream fis=new FileInputStream(path);
BufferedReader in1=new BufferedReader(new InputStreamReader(fis));
// InputStream in = getClass().getResourceAsStream("/config.properties");
props.load(in1);
in1.close();
int value=Integer.parseInt(props.getProperty("value"));
Timer t=new Timer();
t.scheduleAtFixedRate(
new TimerTask() {
#Override
public void run() {
// System.out.println("HELEOELE");
try {
// test.index();
System.out.println("hello ");
} catch (Exception e) {
e.printStackTrace();
}
}
},
0,
value);
}
What I did was I set value as N in a config file where it can be changed by anyone without touching the actual code. So I compiled the jar file, and I placed both config.properties and jar file in same folder or directory. I want to be able to change make N changeable so I don't need to re-compile the jar again and again everytime.
Note: the config properties file is created manually and placed in same directory as the jar. And I am executing the jar in command prompt.
However, it seems when I try to run it, it doesn't recognize the file path.
"main" java.io.FileNotFoundException: .\config.properties (The system cannot find the file specified)
I've looked into many issues regarding reading config files outside of jar file and none of them worked for me. Am I doing any mistake here?
./config.properties is a relative path that points to a config.properties file in the current working directory.
The current working directory, unless changed by System.setProperty("user.dir", newPath), will be the directory from which you launched the JVM currently handling your code.
To get your jar to work as it currently is, you have two ways available :
copy the config.properties file to the directory you are executing java from
change the directory you are running java from to the one that contains the config.properties
You may also consider letting the user specify where to get the properties file from :
String path = System.getProperty("propertiesLocation", "config.properties");
You would then be able to specify a location for the property file when calling your jar :
java -jar /path/to/your.jar -DpropertiesLocation=/path/to/your.properties
Or call it as you did before to search for the properties at its default location of config.properties in the current working directory.
I have an application that writes some data to a plain text index file. It works fine in Netbeans, but when packaged as a jar the index file is created but ends up blank. Here is the relevant code:
System.out.println("Writing Index File");
PrintWriter indexOut = new PrintWriter(new File("index.txt"));
for(int i = 0; i < index.size(); i++)
{
indexOut.println(index.get(i));
}
indexOut.flush();
indexOut.close();
System.out.println("Index complete.");
Why would the apps behavior change when I bundle it as a jar and how can I fix it?
Do you think the index collection has something?
You may want to change the first like to
System.out.println("Writing Index File " + index.size());
You can try debugging the same.
There should be no reason for the app behaviour to change, unless the input to the program changes.
I suspect you are reading some data in your program from a file which is supposed to be relative to your current directory. So you should check if you have dependency on any relative path. If yes convert them to absolute path as first step.
When you run from netbeans the default file path (where a file will land if you just write File("indexOut.txt") ) is the netbeans project folder. If you double-click the jar file, then the default path is the directory containing the jar.
Basically, I have a directory with some files in it. In run configurations I am trying to put the directory as an arguement like so: \(workspacename\directory. Then, the following code should create a list of all the files in that directory:
String directory = args[1];
File folder = new File(directory);
File[] allFiles = folder.listFiles();
ArrayList<File> properFiles = null;
for (File file: allFiles) {
if(file.getName().endsWith(".dat")){
properFiles.add(file);
}
}
the problem i'm facing is that for some reason allFiles is null.
I'll take a guess at what your problem might be:
If your argument is a relative path (as opposed to an absolute path, staring with "/" or "c:/" for example), keep in mind that files will be relative to the working directory of the application.
So new File(directory) will be relative to wherever the application is started. In Eclipse the default working directory is in the project. So if your project is in the top level of the workspace, it will be something like workspacename/project.
You can try printing out folder.getAbsolutePath(), folder.exists() and folder.isDirectory() to help diagnose your problem.
The javadocs say listFiles() will return null if the directory does not actually exist (among other things):
Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
Debug by verifying (debugger or printf) the args[1] value.
Also, it looks like you might be trying to use a substitution variable to insert the workspace location in the path. If so, again, you need to verify (via debugger or printf) that the placeholder is getting replaced properly.
Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running.
Does anyone know the solution to my problem or a better way of reading a text file?
Do not use relative paths in java.io.File.
It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.
Always use absolute paths in java.io.File, no excuses.
For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:
public MyClass() {
URL url = getClass().getResource("filename.txt");
File file = new File(url.getPath());
InputStream input = new FileInputStream(file);
// ...
}
or
public MyClass() {
InputStream input = getClass().getResourceAsStream("filename.txt");
// ...
}
Try giving an absolute path to the filename.
Also, post the code so that we can see what exactly you're trying.
When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.
you can find the current working directory of your process using
String workindDir = new File(".").getAbsoultePath()
Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).
If you're using Eclipse (or a similar IDE), the problem arises from the fact that your program is run from a few directories above where the actual source is located. Try moving your file up a level or two in the project tree.
Check out this question for more detail.
The simplest solution is to create a new file, then see where the output file is. That is the correct place to put your input file into.
If you put the file and the class working with it under same package can you use this:
Class A {
void readFile (String fileName) {
Url tmp = A.class.getResource (fileName);
// Or Url tmp = this.getClass().getResource (fileName);
File tmpFile = File (tmp);
if (tmpFile.exists())
System.out.print("I found the file.")
}
}
It will help if you read about classloaders.
say I have a text file input.txt which is located on the desktop
and input.txt has the following content
i came
i saw
i left
and below is the java code for reading that text file
public class ReadInputFromTextFile {
public static void main(String[] args) throws Exception
{
File file = new File(
"/Users/viveksingh/desktop/input.txt");
BufferedReader br
= new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
output on the console:
i came
i saw
i left