i use this simple code to rename a file when an event happens:
String newFileName = oldFileName + "_" + new Date().getTime();
if the event happens more and more time i will have a string like:
myfile_1372933712717_1372933715279_1372933716234
while i would like to have only the last timestamp...
Of course i could do a substring to remove the string after "_" and replace it with the new timestamp, but let's suppose i will have a file like: myfile_mycomment...mycomment will be replaced and it's not a good thing...
So how could i recognize if there is already a filestamp in the name of the file?!?
You can try to approach this with RegEx, as the timestamps will always have the same pattern. By this, you can differ between comments and timestamps and remove only the timestamps.
This code
String test = "Hallo_Comment_1372933712717_1372933712717";
test = test.replaceAll("_1[0-9_]{12}", "");
System.out.println(test);
generated this output
Hallo_Comment
Assuming your original file name does'nt contains "_"
Before appending split file name with "_" and get always the 0th element from the string array and append the timestamp
Related
Im importing Excel data to Java program. Having a column that should eliminate whitespace in case user mistype on the column.
Example value : "12341 "
i've used
replaceAll("\\s+", "");
replaceAll(" ", "");
StringUtils.trim(stringValue);
However, it still return "12341 " with length :6. It didn't remove the unnecessary white-spaces
EDIT
Complete code for replace return.
stringArray[x] = stringArray[x].replaceAll("\\s+", "");
stringArray[x] = stringArray[x].replaceAll(" ", "");
stringArray[x] = StringUtils.trim(stringArray[x]);
This should work:
stringValue = stringValue.replaceAll(" ", "");
You need to use the returned value.
I too face the same problem and i resolved it by using
text = text.replaceAll("[^\x00-\x7F]", "");
And make sure this will remove your special character too
Ref link :
https://howtodoinjava.com/regex/java-clean-ascii-text-non-printable-chars/
Given the below incoming path, e.g.
C:\cresttest\parent_3\child_3_1\child_3_1_.txt
How can one update and add new dir in between above path to construct below result
C:\cresttest\NEW_PATH\parent_3\child_3_1\child_3_1_.txt
Currently I am using multiple subString to identify the incoming path, but incoming path are random and dynamic. Using substring and placing my new path requires more line of code or unnecessary processing, is there any API or way to easily update and add my new dir in between the absolute path?
By using java.nio.file.Path, you could to the following:
Path incomingPath = Paths.get("C:\\cresttest\\parent_3\\child_3_1\\child_3_1_.txt");
//getting C:\cresttest\, adding NEW_PATH to it
Path subPathWithAddition = incomingPath.subpath(0, 2).resolve("NEW_PATH");
//Concatenating C:\cresttest\NEW_PATH\ with \parent_3\child_3_1\child_3_1_.txt
Path finalPath = subPathWithAddition.resolve(incomingPath.subpath(2, incomingPath.getNameCount()));
You could then get the path URI by calling finalPath.toUri()
Note: this doesn't depend on any names in your path, it depends on the directory depth though, which you could edit in the subpath calls.
Note 2: you could probably reduce the amount of Path instances you make to one, I made three to improve readability.
You may simply insert a path at the second backslash like this:
String path="C:\\cresttest\\parent_3\\child_3_1\\child_3_1_.txt";
final String slash="\\\\";
path=path.replaceFirst(slash+"[^"+slash+"]+"+slash, "$0NEW_PATH"+slash);
System.out.println(path);
Demo
This replaces the first occurrence of \\arbitrarydirname\\ with itself (referred to via $0) followed by NEWPATH\\.
The separator’s source code representation looks a bit odd ("\\\\") as a backslash has to be escaped twice when writing regular expression in a Java String literal.
If you want your operation to be platform independent, you may replace that line with
final String slash = Pattern.quote(FileSystems.getDefault().getSeparator());
Of course, then, the input path must be in the right format for the platform as well.
You can use this simple regex replace:
path = path.replaceAll(":.\\w+", "$0\\\\NEW_PATH");
Your code would be simpler if you used / instead of \ for your path delimiters. eg, compare:
String path = "C:\\cresttest\\parent_3\\child_3_1\\child_3_1_.txt";
path = path.replaceAll(":.\\w+", "$0\\\\NEW_PATH");
with
String path = "C:/cresttest/parent_3.child_3_1/child_3_1_.txt";
path = path.replaceAll(":.\\w+", "$0/NEW_PATH");
Java can handle either delimiter on windows, but on linux only / works, so to make your code portable and more readable, prefer using /.
Just for fun, not sure whether this is what you wanted
public static String addFolderToPath(String originalPath, String newFolderName, int position){
String returnString = "";
String[] pathArray = originalPath.split("\\\\");
for(int i = 0; i<pathArray.length; i++){
returnString = returnString.concat(i==position ? "\\" + newFolderName : "");
returnString = returnString.concat(i!=0 ? "\\" + pathArray[i] : "" + pathArray[i]);
}
return returnString;
}
Call:
System.out.println(addFolderToPath("c:\\abc\\def\\ghi\\jkl", "test", 1));
System.out.println(addFolderToPath("c:\\abc\\def\\ghi\\jkl", "test", 2));
System.out.println(addFolderToPath("c:\\abc\\def\\ghi\\jkl", "test", 3));
System.out.println(addFolderToPath("c:\\abc\\def\\ghi\\jkl", "test", 4));
Run:
c:\test\abc\def\ghi\jkl
c:\abc\test\def\ghi\jkl
c:\abc\def\test\ghi\jkl
c:\abc\def\ghi\test\jkl
I'm writing a text to HTML converter.
I'm looking for a simple way to wrap each line of text (which ends with carriage return) with
<p>.....text.....</p>
Can you suggest some String replacement/regular expression that will work in Java ?
Thanks
String txtFileContent = ....;
String htmlContent = "<p>" + txtFileContent.replaceAll("\\n","</p>\\n<p>") + "</p>";
Assuming,
line delimitter is "\n".
One line is one paragraph.
The end of txtFileContent is not "\n"
Hope this help
Try using StringEscapeUtils.escapeHtml and then adding the tags you want at the beginning end.
String escapeHTML = StringEscapeUtils.escapeHtml(inputStr);
String output = "<p>"+escapeHTML+"</p>";
I am writing a code in which I want user to provide a string of unknown length.. suppose he provided a string.. now I want to get city and country present in that string...
If anybody have any better idea, please share..
As your requirement, you have to build a case where you need to defined all the possibility city or country like Array city= new Array["America","England","China","Myanmar"]; after that now loop your array then read the user defined line from index 0 and each time move your character point +1(do in a loop too)(convert it in String) then search your city pattern to match with the character(String). Your program complexity will increase more and more due to your requirement, I think your complexity will raise up to O(n*n), it is not good for memory.
On my view of point, you should ask from user to get the actual requirement step by step like (Enter City :_ then Enter Country :__) it is better to handle the string.GOOD LUCK!
In the question you never specified the format of the input string but assuming the format is "city, country" then this works
String s = "the name of a city, the name of a country";
String city = s.substring(0, s.indexOf(", "));
String country = s.substring(s.indexOf(", ") + 2);
System.out.println("City = " + city);
System.out.println("Country = " + country);
Well, your questions are very interesting. The program you are writing now is depending on LOGIC and I think there is no such jar files available to get solution on it. It is better to get solution manually. Did you ever think about Dictionary program. Mostly Dictionary words are written in a text file and at run time, the program load that words into an array or some other Collections. This way you can also Load Your file at runtime into a 2D array or collection(mostly HashMap is used). So you can scan your file and load it.Suppose u want to read
Example:
Agra,India
London,England
Yangon,Myanmar
Tokyo,Japan
etc...
` String line;
FileInputStream fstream = new FileInputStream(dataFile);
//dataFile is your file directory
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
HashMap<String,String> divideCityCountry =new HashMap<String,String>();
while((line=br.readLine())!=-1)
{
String[] lineSplit = line.split(",");//use the ',' as delimiter
divideCityCountry.put(lineSplit[0], lineSplit[1]);
} `
Now you can check or get the city and country in the divideCityCountry HashMap().
Hope this may helpful.Good Luck!
I need to get a file name from file's absolute path (I am aware of the file.getName() method, but I cannot use it here).
EDIT: I cannot use file.getName() because I don't need the file name only; I need the part of the file's path as well (but again, not the entire absoulte path). I need the part of file's path AFTER certain path provided.
Let's say the file is located in the folder:
C:\Users\someUser
On windows machine, if I make a pattern string as follows:
String patternStr = "C:\\Users\\someUser\\(.*+)";
I get an exception: java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence for backslash.
If I use Pattern.quote(File.pathSeparator):
String patternStr = "C:" + Pattern.quote(File.separator) + "Users" + Pattern.quote(File.separator) + "someUser" + Pattern.quote(File.separator) + "(.*+)";
the resulting pattern string is: C:\Q;\EUsers\Q;\EsomeUser\Q;\E(.*+) which of course has no match with the actual fileName "C:\Users\someUser\myFile.txt".
What am I missing here? What is the proper way to parse file name?
What is the proper way to parse file name?
The proper way to parse a file name is to use File(String). Using a regex for this is going to hard-wire platform dependencies into your code. That's a bad idea.
I know you said you can't use File.getName() ... but that is the proper solution. If you would care to say why you can't use File.getName() perhaps I could suggest an alternative solution.
If you indeed want to use a regular expressions, you should use
String patternStr = "C:\\\\Users\\\\someUser\\\\(.*+)";
^^ ^^ ^^
instead.
Why? Your string literal
"C:\\Users\\someUser\\(.*+)"
is compiled to
C:\Users\someUser\(.*+)
Since \ is used for escaping in regular expressions too, you'll have to escape them "twice".
Regarding your edit:
You probably want to have a look at URI.relativize(). Example:
File base = new File("C:/Users/someUser");
File file = new File("C:/Users/someUser/someDir/someFile.txt");
String relativePath = base.toURI().relativize(file.toURI()).getPath();
System.out.println(relativePath); // prints "someDir/someFile.txt"
(Note that / works as file-separator on Windows machines too.)
Btw, I don't know what you have as File.separator on your system, but if it's set to \, then
"C:" + Pattern.quote(File.separator) + "Users" + Pattern.quote(File.separator) +
"someUser" + Pattern.quote(File.separator) + "(.*+)";
should yield
C:\Q\\EUsers\Q\\EsomeUser\Q\\E(.*+)
String patternStr = "C:\\Users\\someUser\\(.*+)";
Backslashes (\) are escape characters in the Java Language. Your string contains the following after compilation:
C:\Users\someUser\(.*+)
This string is then parsed as a regex, which uses backslashes as an escape character as well. The regex parser tries to understand the escaped \U, \s and \(. One of them is incorrect regarding the regex syntax (hence your exception), and none of them are what you are trying to achieve.
Try
String patternStr = "C:\\\\Users\\\\someUser\\\\(.*+)";
If you want to solve it by pattern you need to escape your Pattern properly
String patternStr = "C:\\\\Users\\\\someUser\\\\(.*+)";
Try putting double-double-backslashes in your pattern. You need a second backslash to escape one in the patter, plus you'll need to double each one to escape them in the string. Hence you'll end up with something like:
String patternStr = "C:\\\\Users\\\\someUser\\\\(.*+)";
Move from end of string to first occurrence of file path separator* or begin.
File paths separator can be / or \.
public static final char ALTERNATIVE_DIRECTORY_SEPARATOR_CHAR = '/';
public static final char DIRECTORY_SEPARATOR_CHAR = '\\';
public static final char VOLUME_SEPARATOR_CHAR = ':';
public static String getFileName(String path) {
if(path == null || path.isEmpty()) {
return path;
}
int length = path.length();
int index = length;
while(--index >= 0) {
char c = path.charAt(index);
if(c == ALTERNATIVE_DIRECTORY_SEPARATOR_CHAR || c == DIRECTORY_SEPARATOR_CHAR || c == VOLUME_SEPARATOR_CHAR) {
return path.substring(index + 1, length);
}
}
return path;
}
Try to keep it simple ;-).
Try this :
String ResultString = null;
try {
Pattern regex = Pattern.compile("([^\\\\/:*?\"<>|\r\n]+$)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group(1);
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
Output :
myFile.txt
Also for input : C:/Users/someUser/myFile.txt
Output : myFile.txt
What am I missing here? What is the proper way to parse file name?
The proper way to parse a file name is to use the APIs that are already provided for the purpose. You've stated that you can't use File.getName(), without explanation. You are almost certainly mistaken about that.
I cannot use file.getName() because I don't need the file name only; I need the part of the file's path as well (but again, not the entire absoulte path).
OK. So what you want is something like this.
// Canonicalize paths to deal with ".", "..", symlinks,
// relative files and case sensitivity issues.
String directory = new File(someDirectory).canonicalPath();
String test = new File(somePathname).canonicalPath();
if (!directory.endsWith(File.separator)) {
directory += File.separator;
}
if (test.startsWith(directory)) {
String pathInDirectory = test.substring(directory.length()):
...
}
Advantages:
No regexes needed.
Doesn't break if the path separator is something other than \.
Doesn't break if there are symbolic links on the path.
Doesn't break due to case sensitivity issues.
Suppose the file name has special characters, specially when supporting MAC where special characters are allowing in filenames, server side Path.GetFileName(fileName) fails and throws error because of illegal characters in path. The following code using regex come for the rescue.
The following regex take care of 2 things
In IE, when file is uploaded, the file path contains folders aswell (i.e. c:\samplefolder\subfolder\sample.xls). Expression below will replace all folders with empty string and retain the file name
When used in Mac, filename is the only thing supplied as its safari browser and allows special chars in file name
var regExpDir = #"(^[\w]:\\)([\w].+\w\\)";
var fileName = Regex.Replace(fileName, regExpDir, string.Empty);