Final edit: now the code looks like this
InputStream is = getClass().getResourceAsStream("/static/master-key.txt");
String masterKey = null;
Scanner scanner = new Scanner(is);
masterKey = scanner.nextLine();
System.out.println("the master key is " + masterKey);
Original post
I have a problem when reading txt file from resources folder.
This what project structure looks like:
projStructure
When I invoke the following code
System.out.println(getClass().getClassLoader().getResource("static/master-key.txt").getPath());
File mkFile = new File(getClass().getClassLoader().getResource("static/master-key.txt").getPath());
this what happens
/D:/Dropbox/Coding/Intellij%20IDEA/TishenkoKPO/target/classes/static/master-key.txt
java.io.FileNotFoundException:
D:\Dropbox\Coding\Intellij%20IDEA\TishenkoKPO\target\classes\static\master-key.txt (System cannot find the specified path)
I've googled alot but have no clue of why this happens
Edit 1:
Part of the code rebuilt as community suggested (working with file as a resource)
InputStream is = getClass().getResourceAsStream("static/master-key.txt");
String masterKey = null;
Scanner scanner = new Scanner(is);
masterKey = scanner.nextLine();
System.out.println("the master key is " + masterKey); //successfuly outputs the first line if exists
Edit 2: resourcepath should begin with /
InputStream is = getClass().getResourceAsStream("/static/master-key.txt");
InputStream is = getClass().getResourceAsStream("static/master-key.txt");
This is searching for a resource relative to the package / directory of the class that is calling it. It is likely that resource can actually be found relative to the root of the application structure. To do that, add a leading /, like this.
InputStream is = getClass().getResourceAsStream("/static/master-key.txt");
Try this
getResource("resources\static\master-key.txt").getPath());
and if u targeting a path use '\' not '/'.
And u can try
YourClass.class.getResourceAsStream("resources\static\master-key.txt");
or
YourClass.class.getResourceAsStream("static\master-key.txt");
Related
Below is my project like:
projectName
-package
- Util.java
- Test.json
In Util.java, I need to read the content from Test.json file and parse it.
Thus I use:
File currentfile = new File("");//get the current path
String absJsonPath = currentfile.getAbsolutePath() + "/Test.json";
While it did not work when I use a main method to test it. The thing is that the /src/package is lost in the obtained file path and I just got the path of the project.
And, when I deploy the project to weblogic server, I got another new error, the obtained current path is like:
.../DefaultDomain/.
I just want the file path in the file system, which is not related to the server.
What can I do for this? Thanks!
Put your file in resources folder and get it as following:
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("Test.json").getFile());
To read the content you can use following:
StringBuilder result = new StringBuilder("");
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
It's CanonicalPath() not Absolute. Check this out, let me know if it any helps.
Try this to get current path
String currentPath = System.getProperty("user.dir");
If you want to read a file in a specific package. You can use
File jsonFile = new File(getClass().getResource("/Test.json").getFile());
So I have a property file in my project. I need to access it.
Here's the tree structure:
+ Project Name
|--+ folder1
|--+ propertyfolder
|--+ file.properties
Or: Project/propertyfolder/file.properties
Here's what I've tried so far (one at a time, not all at once):
// error: java.io.File.<init>(Unknown Source)
File file = new File(System.getProperty("file.properties"));
File file = new File(System.getProperty("propertyfolder/file.properties"));
File file = new File(System.getProperty("propertyfolder\\file.properties"));
File file = new File(System.getProperty("../../propertyfolder/file.properties"));
And:
InputStream inputStream = getClass().getResourceAsStream("file.properties");
InputStream inputStream = getClass().getResourceAsStream("../../propertyfolder/file.properties");
InputStream inputStream = getClass().getResourceAsStream("propertyfolder/file.properties");
InputStream inputStream = getClass().getResourceAsStream("propertyfolder\\file.properties");
And all variations within getClass(), such as getClass().getClassLoader(), etc.
The error I'm getting is a NullReferenceException. It's not finding the file. How do I find it correctly?
(taken from comment to answer as OP suggested)
Just use File file = new File("propertyfolder/file.properties") but you do need to know where is java process working directory, if you cannot control it try an absolute path /c:/myapp/propertyfolder/file.properties.
You may also use /myapp/propertyfolder/file.properties path without C: disk letter to avoid windows-only mapping. You may use / path separator in Java apps works in Win,Linux,MacOSX. Watch out for text file encoding, use InputStreamReader to given an encoding parameter.
File file = new File("propertyfolder/file.properties");
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader reader = new BufferedReader(isr);
..read...
reader.close(); // this will close underlaying fileinputstream
Inorder to use getClass().resourceAsStream("file.properties") you need to make sure the file is there in the classpath.
That is if your Test.java file is compiled into bin/Test.class then make sure to have file.properties in the bin/ folder along with the Test.class
Otherwise you can use the Absolute Path, which is not advisable.
Did you set System properties to load file.properties from
1) Command line using -Dpropertyname=value OR
2) System.setProperty() API OR
3) System.load(fileName) API?
If you have n't done any one of them, do not use System.getProperty() to load file.properties file.
Assuming that you have not done above three, the best way to create file InputStream is
InputStream inputStream = getClass().getResourceAsStream("<file.properties path from classpath without />");
Properties extends Hashtable so, Each key and its corresponding value in the property list is a string.
Properties props = new Properties();
// File - Reads from Project Folder.
InputStream fileStream = new FileInputStream("applicationPATH.properties");
props.load(fileStream);
// Class Loader - Reades Form src Folder (Stand Alone application)
ClassLoader AppClassLoader = ReadPropertyFile.class.getClassLoader();
props.load(AppClassLoader.getResourceAsStream("classPATH.properties"));
for(String key : props.stringPropertyNames()) {
System.out.format("%s : %s \n", key, props.getProperty(key));
}
// Reads from src folder.
ResourceBundle rb = ResourceBundle.getBundle("resourcePATH");// resourcePATH.properties
Enumeration<String> keys = rb.getKeys();
while(keys.hasMoreElements()){
String key = keys.nextElement();
System.out.format(" %s = %s \n", key, rb.getString(key));
}
// Class Loader - WebApplication : src folder (or) /WEB-INF/classes/
ClassLoader WebappClassLoader = Thread.currentThread().getContextClassLoader();
props.load(WebappClassLoader.getResourceAsStream("webprops.properties"));
To read properties from specific folder. Construct path form ProjectName
InputStream fileStream = new FileInputStream("propertyfolder/file.properties");
If Key:value pairs specified in .txt file then,
public static void readTxtFile_KeyValues() throws IOException{
props.load(new FileReader("keyValue.txt") );
// Display all the values in the form of key value
for (String key : props.stringPropertyNames()) {
String value = props.getProperty(key);
System.out.println("Key = " + key + " \t Value = " + value);
}
props.clear();
}
Maybe its something simple i am over looking, but i need to be able to create sub directories using a list of numbers stored in a txt file. When i use a string literal it creates the directory, but when i switch to using the variable being used for the items in the list it will not. Here is the code block.
private static void GetJarDir() throws URISyntaxException {
CodeSource codeSource = NewJFrame.class.getProtectionDomain().getCodeSource();
File jarFile = null;
jarFile = new File(codeSource.getLocation().toURI().getPath());
jarDir = jarFile.getParentFile().getPath().replace("dist", "").replace("build", "");
mainFolder = jarDir + "Invoices\\";
}
this is the method i use to get the directory for the jar file and append the path with the directory i need to create the sub-directories in, i'm sure this works.
BufferedImage dest = image.getSubimage(0, 3377, 465, 80);
String newDir = new OCR().recognizeEverything(dest);
File theDir = new File(mainFolder + newDir);
new File(mainFolder + newDir.mkdirs();
im using an optical character recognition library to grab an invoice number off of a cropped image. So newDir is the invoice number. Ive printed out the path and it is the correct path, it is just not creating the directory. If i change the variable to the actual invoice number it works, any ideas?
new File(mainFolder + "223545").mkdirs();
so sitting here playing with it ive narrowed the problem down to the string returned from the OCR. It has to be a string or it wouldnt compile...but when i try to parse the string to an int it throws an exception. and it is in fact an integer
I am trying to read 2 files after i read the files i want to get their contents and manipulate the contents of the two files then update a new file which is the output. The files are in the same folder as the program but the program always throws a FileNotFoundException.
Below is my code:-
import java.io.*;
import java.util.Scanner;
public class UpdateMaster {
public static void main(String[] args)
{
String master = "Customer.dat";
String trans = "Transactns.dat";
String newMaster = "Temp.txt";
Scanner inputStreamMaster = null;
Scanner inputStreamTrans = null;
PrintWriter inputStreamNewMaster = null;
try
{
inputStreamMaster = new Scanner(new File(master));
inputStreamTrans = new Scanner(new File(trans));
inputStreamNewMaster = new PrintWriter(newMaster);
}
catch(FileNotFoundException e)
{
System.out.println("Error: you opend a file that does not exist.");
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error.");
System.exit(0);
}
do
{
String transLine = inputStreamTrans.nextLine();
String masterLine = inputStreamMaster.nextLine();
String[] transLineArr = transLine.split(",");
String[] masterLineArr = masterLine.split(",");
int trAccNo = Integer.parseInt(transLineArr[0]);
int sales = Integer.parseInt(transLineArr[1]);
int masterAccNo = Integer.parseInt(masterLineArr[0]);
int balance = Integer.parseInt(masterLineArr[1]);
while(masterAccNo== trAccNo){
inputStreamNewMaster.println(trAccNo+ " , "+masterAccNo);
masterLine = inputStreamMaster.nextLine();
masterLineArr = masterLine.split(",");
masterAccNo = Integer.parseInt(masterLineArr[0]);
balance = Integer.parseInt(masterLineArr[1]);
}
balance = balance + sales;
inputStreamNewMaster.println(masterAccNo+ " , "+balance);
}while(inputStreamTrans.hasNextLine());
inputStreamMaster.close();
inputStreamTrans.close();
inputStreamNewMaster.close();
//System.out.println(" the line were written to "+ newMaster);
}
}
Like #Ankit Rustagi said in the comments, you need the full path of the files if you want to keep the current implementation.
However, there is a solution where you only need the file names: use BufferedReader / BufferedWriter. See here an example on how to use these classes (in the example it uses the full path but it works without it too).
Use absolute path
String master = "C:/Data/Customer.dat";
String trans = "C:/Data/Transactns.dat";
String newMaster = "C:/Data/Temp.txt";
The code works for me, i guess you misspelled some filename(s) or your files are in the wrong folder. I created your files on the same level as the src or the project. Also this is the folder where the files are exspected.
There's nothing wrong with using relative paths like tihis. What's happening is that your program is looking for the files in the directory where you execute the program, which doesn't have to be the folder of the program. You can confirm this by logging the absolute path of the files before you try to read them. For example:
File masterFile = new File(master);
System.out.printf("Using master file '%s'%n", masterFile.getAbsolutePath());
inputStreamMaster = new Scanner(masterFile);
In general you should not hardcode file paths but allow the user to specify them in someway, for example using command line arguments, a configuration file with a well known path, or an interactive user interface.
There is a way to locate the program's class file but it's a little tricky because Java allows classes to be loaded from compressed archives that may be located in remote systems. It's better to solve this problem in some other manner.
Try this:
String current = new java.io.File( "." ).getCanonicalPath();
System.out.println("I look for files in:"+current);
To see what directory your program expects to find its input files. If it shows the correct directory, check spelling of filenames. Otherwise, you have a clue as to what's gone wrong.
I have this error when I am trying to read the file:
Exception in thread "main" java.io.FileNotFoundException: \src\product.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at dao.Inventory.readFile(Inventory.java:30)
at view.InventoryView.init(InventoryView.java:33)
at view.InventoryView.<init>(InventoryView.java:21)
at view.InventoryView.main(InventoryView.java:211)
But the thing is, I have the product.txt in my src folder.
My code is the following:
public void readFile() throws IOException {
// input file must be supplied in the first argument
InputStream istream;
File inputFile = new File("\\src\\product.txt");
istream = new FileInputStream(inputFile);
BufferedReader lineReader;
lineReader = new BufferedReader(new InputStreamReader(istream));
String line;
while ((line = lineReader.readLine()) != null) {
StringTokenizer tokens = new StringTokenizer(line, "\t");
// String tmp = tokens.nextToken();
// System.out.println("token " + tmp);
ActionProduct p = new ActionProduct();
prodlist.add(p);
String category = p.getCategory();
category = tokens.nextToken();
System.out.println("got category " +category);
int item = p.getItem();
item = Integer.parseInt(tokens.nextToken());
String name = p.getName();
System.out.println("got name " +name);
double price = p.getPrice();
price = Double.parseDouble(tokens.nextToken());
int units = p.getUnits();
units = Integer.parseInt(tokens.nextToken());
}
}
I don't think anything is wrong with my code. Also, I saw a similar post about a hidden extension like FILE.TXT.TXT, how would you show a hidden extension in MacOSX?? Any suggestions? (Would there be any other problem besides the hidden extension issue?)
/src/product.txt is an absolute path, so the program will try to find the file in the src folder of your root path (/). Use src/product.txt so the program will use this as a relative path.
It's possible (most likely?) that your Java code is not executing inside the parent folder of src, but instead inside a 'class' or a 'bin' folder with the compiled java .class files.
Assuming that 'src' and 'bin' are in the same directory, you could try ..\\src\\product.txt
See also http://en.wikipedia.org/wiki/Path_(computing)
As other commenters stated, the path is absolute and points to
\src\product.txt which is (hopefully) not where
your sources are stored.
The path separator should be set in an OS-independent manner using
the System.getProperty("path.separator") property. On a Unix system, you'll have trouble with hard coded backslashes as path separators. Keep it portable!
String pathSeparator = System.getProperty("path.separator");
String filePath = "." + pathSeparator + "src" + pathSeparator + "product.txt";
File file = new File(filePath);
or better yet:
// this could reside in a non-instantiable helper class somewhere in your project
public static String getRelativePath(String... pathElements) {
StringBuilder builder = new StringBuilder(".");
for (String pathElement : pathElements) {
builder.append(System.getProperty("path.separator");
builder.append(pathElement);
}
return builder.toString();
}
// this is where your code needs a path
...
new File(getRelativePath("src", "product.txt");
...