unable to findright file path - java

I am facing some problem to fix the right file path.
I have a configuration file and following is the entry in config.properties:
strMasterTestSuiteFilePath="D:\\KeywordDrivenFramework\\MasterTestSuiteFile.xls"
Then i tried to read this property as
Properties prop=new Properties();
prop.load("config.properties")
String strpath=prop.getProperty("strMasterTestSuiteFilePath")
Syso(strpath) //prints above path with single slash as D:\KeywordDrivenFramework\MasterTestSuiteFile.xls
//When i use the same var for File existance check it say not exists
File obj=new File(strpath)
if(obj.exists())
Syso("Exists....")
else
Syso("Does not exist....")
Why it is going to else block, even though the file exists at path?
How to overcome it?
I tried
String str= strpath.replaceAll("\","\\") //but i am getting some syntax error "The method replaceAll(String, String) in the type String is not applicable for the arguments (String)"
Can anyone help me how to overcome this?
Find the code which i am trying, where i am going wrong?
public void LoadMasterTestSuite()
{
String strGlobalConfigSettingFilePath=System.getProperty("user.dir")+"/src/GlobalConfigurationSettings.properties";
FileInputStream objFIS; //Variable to hold FileSystem Objet
File objFile; //Variable to hold File Object
try
{
objFIS = new FileInputStream(new File(strGlobalConfigSettingFilePath));
globalObjProp.load(objFIS);
strMasterTSFilePath=globalObjProp.getProperty("strMasterTestSuiteFilePath");
objAppLog.info("Master Test Suite File Path configured as "+strMasterTSFilePath);
}catch (FileNotFoundException e)
{
objAppLog.info("Unable to find Global Configuration Settings File. So aborting...");
e.printStackTrace();
}catch (IOException e)
{
e.printStackTrace();
}
String str=strMasterTSFilePath.replace("\\", "\\\\");
objFile=new File(str);
System.out.println(str);
if(objFile.exists())
{
LoadTestSuite(strMasterTSFilePath);
}
else
{
objAppLog.info("Master Test Suite File not found at Path: "+strMasterTSFilePath);
System.exit(-1);
}
}

I guess what you wanted to do was:
String str= strpath.replaceAll("\\\\","\\")
\ is a special character in a String. To Treat it like a normal character, put another \ in front of it, so '\' actually is '\\'.
And for your case, I think you want to use .replace() and not .replaceAll().

When you debug, is strpath getting the correct path from the config file? I would also make sure that you're referencing the correct file path (paste the location into Windows Explorer and see if the file exists). If D:\ is a shared drive, use the actual server location.
Also, you can make sure that the extension of the Excel workbook is .xls and not .xlsx.

Related

Path on Ubuntu server in java?

I just did a little project in java, packed the .jar and application.properties to my VPS and wanted to test it there. The tool reads logfiles.
I specified the path to the logfile within the application.properties as follows:
LOGPATH=/folder1/folder2/logs/thelogIwant.log
The path is parsed as follows:
public String makePath(String path) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("application.properties");
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop.getProperty(path);
}
Path logFile = Paths.get(makePath("LOGPATH"));
It even seems to to this right, as the ErrorMessage states:
SEVERE: /folder1/folder2/logs/thelogIwant.log (No such file or directory)
The logfile is being created by another application and therefore in another directory than the .jar I am running.
The path exists on my VPS and I can navigate to and through it.
Can someone point me in the right direction? What's going wrong here?
Things I tried:
Specify path with "~/folder1/..."
Specify path with "folder1/..."
I can think of a few possible explanations:
The pathname in your config file is wrong; e.g. there is a typo or some other discrepancy that you didn't notice.
You are loading a different property file to the one that you think.
There is a mismatch between the property name in the file and the name that your tool uses.
The other application didn't create the log file
Permissions: your tool may be running as a user that isn't permitted to read one of the directories on the path.
SELinux in enforcing mode can prevent an application (e.g. running as a service) from accessing files.
Homoglyphs, either in the property file1, your source code or the name of the file in the file system.
The things that you tried are unlikely to work. A correct absolute pathname is more robust than a relative pathname, and Paths.get doesn't know how to deal with ~. (The expansion of ~ is a shell feature ....)
I would try this:
Modify your tool to output the value of the "LOGPATH" property ... enclosed in quote characters so that you can see any spurious whitespace characters at the beginning / end of the value.
Run the tool.
Using copy-and-paste, see if you can open the file using exactly the pathname that your tool uses.
In short, verify that the pathname you are actually using is what you expect it to be.
1 - In practice, classic format property files are encoded in LATIN-1, so this is impossible.
I was able to fix this, thanks #Steven for your help!
I used the pwd command when in the directory the files are in and recognized that the true absolute path starts with /home/myusername/folder1/...
Works fine now.

Where is the file stored to be read by FileInputStream?

I'm getting 'File not found!' no matter what I do.
FileInputStream fin;
try {
fin = new FileInputStream("foo.txt");
String str = IOUtils.toString(fin);
System.out.println(str);
} catch (FileNotFoundException f) {
System.out.println("File not found!");
}
Do you have a foo.txt in the directory that you are working in?.
If you are using command window and are at a location say, C:\, then your code expects foo.txt to be present there.
If your foo.txt is present in some other path, use the full path in your code.
If you temporarily add this line to your code:
System.out.println(new File("foo.txt").getAbsolutePath());
it should tell you where it expects to find the file. If the file isn't in that location, then you'll either have to specify the path or move the file so that it is.
Make sure you're using the correct path. Try right-clicking and go on to Properties and check the file's path. Copy and paste the path and replace all the \ to either / or \\.

How to create a working .jar for a java project w/ excel input and System.out.print output?

I created this java project that basically gets data from an user determined excel file and uses Syste.out.println() to display the results. It works as I want it to in eclipse, however when I exported is as a .jar file, it doesn't work properly. It prompts for the excel file location to be entered, however, does not display the output, not even an error. I do not know how to do it from the terminal so I'm running it by double-clcking it. Also, I want the user to choose any excel file they want, so what should they write down as the location when prompted to do so? Right now, the excel file is in the same directory as the project. So just the name of the excel file is enough input, but what if it is not in the directory, how do i show it's location then?
Thank you
First of all, in your JAR file the file META-INF/MANIFEST.MF must contain your main class (i.e. the class with the main() method), with a line like this:
Main-Class: mypackage.MyMainClass
Make sure your settings in Eclipse are generating this line when generating the JAR file.
You can run it from the terminal with java -jar yourapp.jar however I presume that you have some extra libraries you need to include in the classpath with the -cp switch.
The working directory is normally the directory from where you are running the application. If you want to specify a different path it has to be either relative to that, or absolute.
An absolute path in windows would be something like: "C:\mydatafolder\myexcelsheet.xls"
An absolute path in Unix would be something like: "/home/myaccount/mydatafolder/myexcelsheet.xls"
You need to read System.in to get the file path, with a function like this:
private static String getFilePath () {
String filePath = null;
while (true) {
System.out.println("Please input the path of the file:");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
filePath = br.readLine();
File file = new File(filePath);
if (!file.exists()) {
System.out.println("Sorry, invalid file path. Please try again.");
} else {
return filePath;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Sorry, unexpected error happened, Please try again.");
}
}
}

Read file with whitespace in its path using Java

I am trying to open files with FileInputStream that have whitespaces in their names.
For example:
String fileName = "This is my file.txt";
String path = "/home/myUsername/folder/";
String filePath = path + filename;
f = new BufferedInputStream(new FileInputStream(filePath));
The result is that a FileNotFoundException is being thrown.
I tried to hardcode the filePath to "/home/myUserName/folder/This\\ is\\ my\\ file.txt" just to see if i should escape whitespace characters and it did not seem to work.
Any suggestions on this matter?
EDIT: Just to be on the same page with everyone viewing this question...opening a file without whitespace in its name works, one that has whitespaces fails. Permissions are not the issue here nor the folder separator.
File name with space works just fine
Here is my code
File f = new File("/Windows/F/Programming/Projects/NetBeans/TestApplications/database prop.properties");
System.out.println(f.exists());
try
{
FileInputStream stream = new FileInputStream(f);
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
f.exists() returns true always without any problem
Looks like you have a problem rather with the file separator than the whitespace in your file names. Have you tried using
System.getProperty("file.separator")
instead of your '/' in the path variable?
No, you do not need to escape whitespaces.
If the code throws FileNotFoundException, then the file doesn't exist (or, perhaps, you lack requisite permissions to access it).
If permissions are fine, and you think that the file exists, make sure that it's called what you think it's called. In particular, make sure that the file name does not contain any non-printable characters, inadvertent leading or trailing whitespaces etc. For this, ls -b might be helpful.
Normally whitespace in path should't matter. Just make sure when you're passing path from external source (like command line), that it doesn't contain whitespace at the end:
File file = new File(path.trim());
In case you want to have path without spaces, you can convert it to URI and then back to path
try {
URI u = new URI(path.trim().replaceAll("\\u0020", "%20"));
File file = new File(u.getPath());
} catch (URISyntaxException ex) {
Exceptions.printStackTrace(ex);
}

How to read file from relative path in Java project? java.io.File cannot find the path specified

I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

Categories

Resources