Eclipse not finding file? - java

I am using eclipse and I have my text file in the correct directory (src folder). I just want to read the file and count all the words in it. For some reason I am getting a file not found exception being thrown.
here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Tester {
public static int getSizeOfDictionary(File dictionary)
throws FileNotFoundException {
int count = 0;
Scanner reader = new Scanner(dictionary);
while (reader.hasNextLine()) {
reader.nextLine();
count++;
}
reader.close();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
File test = new File("words.txt");
System.out.println(getSizeOfDictionary(test));
}
}

You could use this.getClass().getResource("words.txt") which will find that file on the current classpath.
From the main method you could use: Tester.class.getResource("words.txt")

when eclipse launches jvm it sets current directory to project base directory generally (unless you modify the default current directory)
${workspace_loc}/project_name
so you need to change your File initialization to
File test = new File("src/words.txt");
Note:
It will just be limited to this project structure, if you export it to jar it will not work any more, I assume you just need it as part of exercise

You have to use property class to access your file within class-path and source folder
you can try like:
this.getClass().getResourceAsFile("words.txt")

Related

How to read the file entry with same name in multiple library jars with spring boot?

I have a spring application with multiple dependent libraries that have the inner properties/xml that I want to read.
test-app.jar
dep1.jar
dep2.jar
dep3.jar
...
Each of the dep1/2/3 jars have the file called META-INF/config.properties which contains the files to further read within that dependent jars.
I tried the ResourceUtils.getURL("classpath:/META-INF/config.properties"), but it always reads from the first dependent file.
How can I read from each jars that contains the same name?
I found this solution after searching:
final Enumeration<URL> resEnum =
MyClass.class.getClassLoader()
.getResources("META-INF/config.properties");
final List<URL> resources =
Collections.list(resEnum);
//Copied from riptutorial.com
Refs:
https://riptutorial.com/java/example/19290/loading-same-name-resource-from-multiple-jars
https://stackoverflow.com/a/6730897
Updated solution:
package abc;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
public class MultipleClasspathEntries {
public static void main(String[] args) throws IOException {
final Enumeration<URL> resEnum =
MultipleClasspathEntries.class.getClassLoader()
.getResources("META-INF/MANIFEST.MF");
while (resEnum.hasMoreElements()) {
System.out.println(resEnum.nextElement());
}
}
}
//Copied from riptutorial.com
$JAVA_HOME/bin/javac abc/*.java
$JAVA_HOME/bin/java -cp /c/so-67847004/commons-lang-2.4.jar:/c/so-67847004/commons-collections-3.2.1.jar:. abc.MultipleClasspathEntries
Output:
jar:file:/C:/so-67847004/commons-lang-2.4.jar!/META-INF/MANIFEST.MF
jar:file:/C:/so-67847004/commons-collections-3.2.1.jar!/META-INF/MANIFEST.MF

Cannot read the array length because "<local1>" is null

I am making a stock market simulator app in java, and there is an issue in the deleteHistoryFiles() method. It says that array is null. However, I have no idea what array this error is talking about.
Here's the code (I've deleted some methods to save space):
package stock.market.simulator;
import java.util.Random;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StockMarketSimulator {
// Path to where the files are stored for rate history
// USE WHEN RUNNING PROJECT IN NETBEANS
//public static final String HISTORYFILEPATH = "src/stock/market/simulator/history/";
// Path to history files to be used when executing program through jar file
public static final String HISTORYFILEPATH = "history/";
public static void main(String[] args) throws IOException {
accountProfile accProfile = accountCreation();
stockProfile[][] stockProfile = createAllStocks();
deleteHistoryFiles(new File(HISTORYFILEPATH));
createHistoryFiles(stockProfile);
mainWindow window = new mainWindow(accProfile, stockProfile);
recalculationLoop(stockProfile, window);
}
// Procedure to create the history files
public static void createHistoryFiles(stockProfile[][] stocks) throws IOException {
String fileName;
FileWriter fileWriter;
for (stockProfile[] stockArray : stocks) {
for (stockProfile stock : stockArray) {
fileName = stock.getProfileName() + ".csv";
fileWriter = new FileWriter(HISTORYFILEPATH + fileName);
}
}
}
// Procedure to delete the history files
public static void deleteHistoryFiles(File directory) {
for (File file : directory.listFiles()) {
if (!file.isDirectory()) {
file.delete();
}
}
}
}
I got the same exception in exactly the same scenario. I tried to create an array of files by calling File.listFiles() and then iterating the array.
Got exception Cannot read the array length because "<local3>" is null.
Problem is that the path to the directory simply does not exist (my code was copied from another machine with a different folder structure).
I don't understand where is <local1> (sometimes it is <local3>) comes from and what does it mean?
It should be just like this: Cannot read the array length because the array is null.
Edit (answering comment) The sole interesting question in this question is what is a <local1>
My answer answers this question: <local1> is just an array created by File.listFiles() method. And an array is null because of the wrong path.

Why does File method rename() delete files?

I wanted to remove the spaces that Windows puts in filenames.
I ran the following code to rename all the files in a test directory thus. The result: all the files disappeared.
I am puzzled as to why.
import java.io.*;
public class FileRenamer {
public static void main(String[] args) {
for (File file: (new File("O:\\test0")).listFiles())
file.renameTo(new File(file.getName().replaceAll("\\s","")));
System.exit(0);
}
}
TL;DR: You are moving the file.
You list the files in a directory "O:\\test0.
For each such file you then create a String:
file.getName().replaceAll("\\s","")
You end up with:
new File("someFileName")
So you have called:
file.renameTo(new File("someFileName"))
Now, someFileName is not an absolute path; but a relative path. So you have moved from O:\\test0\\some File Name to someFileName, where someFileName is in the directory of the program.
P.S. there is no need to call System.exit(0).
Yes, I found the files had been moved to my class file directory.
Boris's tip about relative vs. absolute paths showed me the solution: to use the
public File(File parent, String child)
constructor for the new abstract File object. The following code did the job correctly.
import java.io.*;
public class FileRenamer {
public static void main(String[] args) {
File dir = new File("O:\\test0");
for (File file: dir.listFiles())
file.renameTo(new File(dir, file.getName().replaceAll("\\s","")));
}
}

Open any file from within a java program

Opening files in java seems a bit tricky -- for .txt files one must use a File object in conjunction with a Scanner or BufferedReader object -- for image IO, one must use an ImageIcon class -- and if one is to literally open a .txt document (akin to double-clicking the application) from java, this code seems to work:
import java.io.*;
public class LiterallyOpenFile {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("notepad Text.txt");
}
}
I'm not positive, but I think other file-types / names can be substituted in the parenthesis after exec -- anyway, I plan on opening certain files in a JFileChooser when the user clicks on a file to open (when the user clicks on a file, the path to the file can be obtained with the getSelectedFile() method). Though I'm more specifically looking to be able to open an Arduino file in the Arduino IDE from a java program, like a simulated double-click.. perhaps something like this?
import java.io.*;
public class LiterallyOpenFile {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("Arduino C:\\Arduino\\fibonacci_light\\fibonacci_light.ino");
}
}
A point in the right direction would be appreciated.
Have you tried this? If there is a registered program for your file in windows, this should work. (i.e. the default application should open the file)
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
The file parameter is a File object.
Link to API
Link to use cases and implementation example of the Desktop class
This is what I do in my projects using java.awt.Desktop
import java.awt.Desktop;
import java.io.IOException;
import java.io.File;
public class Main
{
public static void main(String[] args) {
try {
Desktop.getDesktop().open(new File("C:\\Users\\Hamza\\Desktop\\image.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}

Xtend how to get full path of current working directory

I have written a grammar that allows the user to input a relative path. (e.g. "../../temp/out/path"
May aim is to get the absolute path based on the input from the user, and the absolute path of the current working directory so that I can also check if the input path is valid or not.
Is there libraries or built in functions that I can use to get the absolute path?
Something similar to C's _getcwd() function.
Yes, Java has a File class. You can create one by calling this constructor which takes a String. Then you can call getAbsolutePath() on it. You can call it like this:
package com.sandbox;
import java.io.File;
public class Sandbox {
public static void main(String[] args) {
File file = new File("relative path");
String absolutePathString = file.getAbsolutePath();
}
}
This will print a complete absolute path from where your application has initialized.
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +System.getProperty("user.dir"));
}
}

Categories