absolute path parameter java - java

I am trying to get the absolute path of working directory, and pass it to a method.
I am getting the path in the form
C:\eclipse\workspace\file.txt
but eclipse must receive it in the form:
C:\\eclipse\\workspace\\file.txt
So I am doing a replace, but it works only for one char, how to modify it?
String path = new File("").getAbsolutePath();
path = path.replace( '\\', '\\\\' );
something = method.read(path+"\\file.txt");

Change this:
path = path.replace( '\\', '\\\\' );
To this:
path = path.replaceAll( "\\", "\\\\" );

try using the replaceAll method.

Just use double quotes to represent more than one char. It's then called a String.
path = path.replace("\\", "\\\\");
Note that this requires a minimum of Java 1.5 to work.
See also:
The Java Tutorials - Learning the language - Strings

You should use:
public String replaceAll(String regex,
String replacement)
Replaces each substring of this string
that matches the given regular
expression with the given replacement.

If you just want the current working directory, the simplest approach is this:
String currentdir = System.getProperty("user.dir");

you can use path = path.replaceAll( '\\', '/' ); it works

Not sure if this will help.. I ran into the same issue with the application I am building.
In my app, I basically use JFileChooser to graphically select the file I want. Long story short, the absolute path of the selected file comes back as "C:\Documents and Settings....\xCBL.xml"
The path was then passed to another class for manipulation, however it failed because of the single '\'. The fix -
String absPath = file.getAbsolutePath();
System.out.println("File Path:"+absPath);
String filePath = absPath.replaceAll("\\\\", "\\\\\\\\");
System.out.println("New File Path:"+filePath);
Output:
File Path:C:\Documents and Settings\tanzim.hasan\workspace\XML to Java\xcbl.XML
New File Path:C:\\Documents and Settings\\tanzim.hasan\\workspace\\XML to Java\\xcbl.XML
Hope the above helps.

Related

FileNotFoundException while trying to open a File

I am trying to d file = new file (location) while location of file is absolute path with somethign like this : \\test\hold\REPO/TEST/Letter/123.pdf
I am getting file not found exception while files are there in this path. what could be going wrong? can i have path with both forward and backward slash?
String separator = System.getProperty("file.separator");
So location can be rewritten to
location=separator+"test"+separator+"hold"+separator +"REPO"+separator "TEST"+separator+"Letter"+separator+"123.pdf";
In this case no need to think about underlying OS
You need two slashes in a string literal to represent one in the filename. Try
"\\\\test\\hold\\REPO/TEST/Letter/123.pdf"
or better still
"//test/hold/REPO/TEST/Letter/123.pdf"
There is never a need to use a backslash in a filename in Java.
Try adding quotes around the filename.
You can write your code without single backward slashes.if you want to use back-word slashes use \\ instead of \ .A single backward slashes create a problem if you put it inside the String literal.So you can write you code in multiple ways to avoid your exceptions.
1) File f=new File("\\test/hold/REPO/TEST/Letter/123.pdf");
2) File f=new File("\\test\\hold\\REPO/TEST/Letter/123.pdf");
3) File f=new File("\\test\\hold\\REPO\\TEST\\Letter\\123.pdf");
4) File f=new File("/test/hold/REPO/TEST/Letter/123.pdf");
you can use :-
InputStream input = new URL("\\test\hold\REPO/TEST/Letter/123.pdf").openStream();
or
File file = new File(location);
where location=\\test\hold\REPO/TEST/Letter/123.pdf; and Check Using SOP statement whether URL is Call properly or not . hope it will help you to fine better solution

Concatenating Strings in Java generates between-in null

This question looks like very similar to: Concatenating null strings in Java
But my issue is some different.
I want to build an absolute path to a file:
String path = properties.get("path"); // returns /home/myuser/relativepath/ , ends with bar /
String file = currentFile; // currentFile values "file.txt"
String result = path + file; // this results in /home/myuser/relativepath/nullfile.txt
Why is there than 'null' text? That's the reason my application does not work now.
I have review it in Windows and Linux.
In Windows it works perfectly.
In Linux, I have this issue.
I uploaded properties file and then, edited with vi command.
Maybe is this the problem?
Shouldn't I use this way to generate an absolute path, and use File.Separator property in Java?
EDIT: I have post my final right answer with detailed steps. I hope it would be useful.
My bet (though I have not seen Java behave this way) is there's a null-ish character (such as a carriage return) of some sort in your properties file which Windows handles at the OS level so Java/Properties doesn't see it.
As a first pass, try printing the length and last few characters of your path string, e.g.:
for(int i = Math.max(0, path.length()-5); i < path.length(); i++) {
System.out.print(path.charAt(i)+":"+((int)path.charAt(i))+" ");
}
System.out.println(path.length());
Willing to bet the last character, on Linux, is not what you'd expect. The right fix would then be to clean up your properties file so that it's compatible on both OSes.
Well, the complete and detailed steps to fix my issue are these (maybe any of them could not be necessary, but I prefer to write them all):
Create config file in Linux with vi, emacs, ... (not upload file from Windows).
Edit file with vi, emacs... At the end of each path, do not include directory separator character ( / ).
Check variables before contatenate them. Make sure they don't have any space and other unexpected character.
Concatenate variables with:
String result = path + File.separator + file;
I hope this would be useful. Thank you all for your suggestions.
Regards
What do you expect?
Yo´re doing a String result = path + result;
int a = 1 + a would be similar... don´t use a variable to init itself.
(That can´t be your code in the first place, if you´re getting this output.)
result is path+file :
String path = properties.get("path");
String file = currentFile;
String result = path + file;
^
change here
the result is: /home/myuser/relativepath/file.txt

Windows escape sequence issue with file path in java

I need to use windows file path to do some operation on files but i am getting invalid escape sequence error.
File f = new File("C:\test");
the system accepts only " \\ " or "/" but if I copy file path from windows it is with "\".
how can i solve this issue
Use File.separator in place of "".
File f = new File("C:"+File.separator+"test");
File.separator returns "" and it is not treated as an escape character.
If your file test.txt is saved in folder D:/MyFloder/MyPrograms you can do something like this
File f = new File("D:"+File.seperator+"MyFloder"+File.separator+"MyPrograms"+File.separator+"test.txt");
EDIT
You don't need to worry about OS
For Unix : File.separator = /
For Windows : File.separator = \
\ is the escape character in Java Strings. Use \\ instead.
"C:\\test" resolves to the String C:\test
You can use \\ or / but / is better because it is OS-independent.
Replace the single backslash in the path with a double backslash or a single forward slash to solve your issue.
Internally, Java will convert it to the file seperator of the OS
File f = new File("C:\\test"); is correct.
You are not creating a File with the path "C:\\test" here. You are creating a File with the path "C:\test". The \\-to-\ conversion happens when you compile the program - by the time your program is running, the double backslashes are gone.
The same for String - String s = "C:\\test"; does not create a string with two backslashes, only one.
You can think of it this way: the string does not actually have two backslashes, but you have to write it that way to put it in your code.
You might be wondering why that is - it's because backslashes are used to insert special characters in strings. When you type \t in a string it inserts a tab, for example. If you want to insert a backslash, then t, you type \\t.
you can use '/' (as in Linux) in paths since Windows XP, so forget about \
Use java.nio.file.Path instead of java.io, you'll not have problem with escape sequence character :
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("C:\test");

reconstructing a file path in java

I have a file path location as such:
Properties readProp = \\192.168.41.84\dev\config\dev\config.properties
how can I manipulate it so I remove the portion of config.properties
and replace it with test\config.properties
so the new Properties location would be:
Properties readProp = \\192.168.41.84\dev\config\dev\test\newconfig.properties
?
thanks for your time and effort
Make sure you escape any backslashes you have as you build the string.
String path = "\\\\192.168.41.84\\dev\\config\\dev\\config.properties";
System.out.println(path);
int lastBackSlash = path.lastIndexOf("\\");
//+1 to include lastBackSlash
String newPath = path.substring(0, lastBackSlash + 1) + "test" + path.substring(lastBackSlash);
System.out.println(newPath);
Prints
\\192.168.41.84\dev\config\dev\config.properties
\\192.168.41.84\dev\config\dev\test\config.properties
This article like this is also decent read. Treating paths as strings can be dangerous.
http://twistedoakstudios.com/blog/Post4872_dont-treat-paths-like-strings
However, if your careful, know what how your string functions behave(or look them up), and you don't have off by 1 errors... then treating the paths like strings should be pain free. But you will have no guarantee that the path is valid... while a path builder library would give you that assurance.

file path Windows format to java format

I need to convert the file path in windows say C:\Documents and Settings\Manoj\Desktop for java as C:/Documents and Settings/Manoj/Desktop .
Is there any utility to convert like this.?
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
path = path.replace("\\", "/");
// or
path = path.replaceAll("\\\\", "/");
Find more details in the Docs
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
String javaPath = path.replace("\\", "/"); // Create a new variable
or
path = path.replace("\\", "/"); // Just use the existing variable
Strings are immutable. Once they are created, you can't change them. This means replace returns a new String where the target("\\") is replaced by the replacement("/"). Simply calling replace will not change path.
The difference between replaceAll and replace is that replaceAll will search for a regex, replace doesn't.
Java 7 and up supports the Path class (in java.nio package).
You can use this class to convert a string-path to one that works for your current OS.
Using:
Paths.get("\\folder\\subfolder").toString()
on a Unix machine, will give you /folder/subfolder. Also works the other way around.
https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Just check
in MacOS
File directory = new File("/Users/sivo03/eclipse-workspace/For4DC/AutomationReportBackup/"+dir);
File directoryApache = new File("/Users/sivo03/Automation/apache-tomcat-9.0.22/webapps/AutomationReport/"+dir);
and same we use in windows
File directory = new File("C:\\Program Files (x86)\\Jenkins\\workspace\\BrokenLinkCheckerALL\\AutomationReportBackup\\"+dir);
File directoryApache = new File("C:\\Users\\Admin\\Downloads\\Automation\\apache-tomcat-9.0.26\\webapps\\AutomationReports\\"+dir);
use double backslash instead of single frontslash
so no need any converter tool just use find and replace
"C:\Documents and Settings\Manoj\Desktop"
to
"C:\\Documents and Settings\\Manoj\\Desktop"
String path = "C:\\Documents and Settings\\someDir";
path = path.replaceAll("\\\\", "/");
In Windows you should use four backslash but not two.

Categories

Resources