java: how to append text in a String after a certain index - java

i have a path
C:\Users\abc xyz\Desktop\test.docx
I want to change in into
C:\Users\sara waheed\Desktop\~$sara.docx
for that first i got the last index of backslash now i want t append '~$' after the last backslash
String str=path.toString();
int index = str.lastIndexOf('\\');
Note
I do not know the value of the path in advance
how can i achieve that

In general, you should use java.nio.file API when manipulating paths, so that it can avoid platform dependent assumptions.
String str = path.getFileName().toString();
// The string concatenation way:
if(str.endsWith(".docx")) { // should we check the beginning of fname?
// maybe it already has the prefix?
path = path.resolveSibling("~$" + str);
}
System.out.println(path);

Since you're representing files, I suggest using the Path api. You can modify any part of the path without messing with the rest.
Path file = Paths.get("C:\\Users\\abc xyz\\Desktop\\test.docx");
Path lock = file.resolveSibling("~$" + file.getFileName());
To interact with these paths, go ahead and look at the Files class.
Files.touch(lock);
Or alternatively using the classic way via path.toFile()
By the way, these are all in the java.nio.file package.

Related

Split directory path with another path

I read the directory path using system properties in java which will work both in windows and Linux based systems. Now I need to split this path with only a portion of the path to retrieve the rest. eg., C:\Test1\Test2\Test3\Test4
I need to split the above path with C:\Test1\Test2 and retrieve Test3\Test4.
When I get this as string and use split function that will give me error as illegal character because of "\" character. If I plan to escape this character with "\\", this may not work in Linux box. Is there a way I can make this work both in Linux and Windows?
Use the below approach.
//Windows
String s = "C:\\Test1\\Test2\\Test3\\Test4";
String[] output = s.split(("/".equals(File.separator))? File.separator : "\\\\" );
//output: [C:, Test1, Test2, Test3, Test4]
//Linux:
String linuxString = "/Test1/Test2/Test3/Test4";
String[] linuxOutput = linuxString.split(("/".equals(File.separator))? File.separator : "\\\\" );
//output: [, Test1, Test2, Test3, Test4]
Hope this will solve the issue.
You are looking for File.separator. Use it to split your string.
From the docs,
The system-dependent default name-separator character, represented as a string for convenience.
The pattern passed to String.split has the regular expression syntax, thus the java.util.regex package is the place to look for additional tools for dealing with them, like quoting a string to enforce literal matching.
So a solution only using system properties and string operations would look like
String path=System.getProperty("your.property"), sep=System.getProperty("file.separator");
for(String s: path.split(Pattern.quote(sep)))
System.out.println(s);
However, there is no reason not to use the dedicated APIs:
Path path = Paths.get(System.getProperty("your.property"));
if(path.isAbsolute()) System.out.println(path.getRoot());
for(Path p: path)
System.out.println(p);
Note that this also handles root paths correctly, i.e. on Windows, the root of a drive is like C:\, not C:, and on Linux, the root is /, not an empty string, and both cases are not handled correctly when just splitting at the separator chars.
Even before Java 7, there was an API that could handle this:
File path = new File(System.getProperty("your.property"));
for(File f = path; f != null; f = f.getParentFile())
System.out.println(f.getName().isEmpty()? f.getPath(): f.getName());
though the code will iterate the elements in the opposite order.
Note, how simple your specific task of splitting at two levels above the path becomes with the dedicated API:
Path path = Paths.get(System.getProperty("your.property"));
Path first = path.getParent().getParent(), second = first.relativize(path);
System.out.println("first: "+first);
System.out.println("second: "+second);
You can use separator when you are building a file path.
Use java.io.File.separator

Is their any way to eliminate two backward slash to one in Eclipse

I came to a scenario while using eclipse, in which if i use two back slash in below mention function.
"private Keywords(){
try{
OR=new Properties();
FileInputStream fs=new FileInputStream(System.getProperty("user.dir")+"**\\src\\com\\config\\OR.properties"**);
OR.load(fs);
"
this function works but if I use single slash it won't work . Is their way that i would be able to use single backward slash only while giving a source path..
Your question has nothing to do with Eclipse.
You need to escape back-slashes in Strings, as they are themselves an escape character.
What you can eventually use to somewhat "shorten" your code is the system property System.getProperty("file.separator"), then assign it to some constant and use that reference instead.
But that's close to cosmetics.
You can use the 2 backslashes as a single variable say,
String separator = "\\";
String file_path = "src"+separator +"com"+separator +"config"+separator +"OR.properties";
System.out.println("File Path is :: " + file_path);
Or as Mena Suggested, you can use:
String separator = System.getProperty("file.separator");
Get it straight with your String literals
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html

How can I convert the unsafe characters in a relative file name into a safe version using the Jersey UriBuilder?

I have two strings. One names a folder's absolute (or relative) path. The other names a file name with potentially unsafe characters:
String folder = "C:\a\b\c\dir";
Sting file = "file name: contains-unsafe_characters?" + ".txt"
I want to smash these to strings together literally in the form:
String absPath = folder + SYSTEM_INDEPENDENT_PATH_SEPERATOR + convertToPercentOctal(folder);
Now, there are probably one million approaches to try to do this:
UriBuilder folderBuilder = UriBuilder.fromPath(folder);
UriBuilder fileBuilder = UriBuilder.fromPath(file);
URI completeFileName = folderBuilder.build().resolve(fileBuilder.build());
or:
URI completeFileName = UriBuilder.fromPath(folder).path(file).build();
etc.
The first block of code fails because there may be a : in the file name. If that is the case, UriBuilder will try to parse it as the optional scheme:. The second way fails because it returns the first and second half converted to %octal notation separated by a system dependent '/' character.
Is there a way concatenate a two strings, convert the result to a writable file name, and return a valid URI I can use to create the file?

How to format system path to a file in java?

I want to read a file say c.txt in java in windows. So can anybody suggest me that how can I format a system path to a file say D:\a\b\c.txt to D:/a/b/c.txt in java? I know it will work like this D:\\a\\b\\c.txt but I want to use this D:/a/b/c.txt. Thanks!
I'm not sure of your problem but rarely is it good practice to hard code / or \. Use Java's File.separator to help you.
You could use the char replace: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace%28char,%20char%29
Example:
String pathToFile = "D:\\a\\b\\c.txt";
pathToFile = pathToFile.replace('\\','/'); <-- with ' and not "
Documentation of replace(char, char):
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
You can use File API
File f = new File("c.txt");
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
or just simply substring
String fname = "D:\\a\\b\\c.txt".replace('\\', '/');
System.out.println(fname);
String file="D:\\a\\b\\c.txt";
file=file.replace('\\','/');
System.out.println(file);
output D:/a/b/c.txt
But if you are trying to make it more platform dependent you should use File.separator (for replacement based on Strings) or File.separatorChar (for replacement based on chars).

string cutting challenge to get one dir level up efficently

what is the most efficient way to get one directory tree level up ?
i am looking for most efficient use of string class method to
getting e:\files\report\fruits from e:\files\report\fruits\apples
I think you are better off just using
File f = new File("e:\\files\\report\\fruits\\apples");
String parent = f.getParent();
If you insist on using String only and assuming '\' is the path separator, you can do something like this:
String s = "e:\\files\\report\\fruits\\apples";
String parent = s.substring(0, s.lastIndexOf('\\'));
But you have to beware of edge cases like there being no character '\' found.
I wouldn't do this by "string bashing" because it will embed all sorts of platform dependencies on pathname syntax into your code. Instead, use the java.io.File class.
String parent = new File("e:\files\report\fruits\apples").getParent();
or better still:
File parent = new File("e:\files\report\fruits\apples").getParentFile();
Stephen makes a valid point about platform dependency, but here's what you asked for:
String dir = "e:\\files\\report\\fruits\\apples";
String parent = dir.replaceAll("\\\\[^\\\\]+$", "");

Categories

Resources