Get path with quotes from JFileChooser? - java

Is it possible to let user enters a path with quotes in JFileChooser and get this path without quotes?
For example the user puts: "c:\path\to\File" in the File name text field. but when I got the selected file I got the current directory + "c:\path\to\File". Is their a way to solve this problem?
Thanks,

You could do something like so:
String str = "\"C:\\foor\\bar\"";
System.out.println(str);
String newStr = str.replaceAll("\"?(.+?)\"?", "$1");
System.out.println(newStr);
prints:
"C:\foo\bar"
C:\foo\bar
This will remove the quotes (") which are exactly at the beginning and end of the string. The ? in the regular expression denotes that the quotes might not be there, so for instance, the following should all yield the same result:
"C:\foo\bar"
"C:\foo\bar
C:\foo\bar"
C:\foo\bar
However, to my knowledge, the " character does not make part of a valid file path, so you might get around just by doing: str.replaceAll("\"","");.
EDIT: Seeing your comment and question edit, I made this short piece of code which seems to do what you are after. That said, I will not be removing my previous answer just in case someone else might find it useful.
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Hello");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(f) == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file.getName().contains("\""))
{
Pattern pattern = Pattern.compile("\"?(.*?)\"?");
Matcher m = pattern.matcher(file.getName());
if (m.matches())
{
System.out.println("Group Found: " + m.group(1));
}
}
}
This seems to do what you are after, I have pasted the following in the File text box: "C:\foo\bar.txt" and the code printed C:\foo\bar.txt, excluding the initial segment.

Related

How to replace slashes

I want to replace a single slash with double slashes in a path, but leave double slashes unaffected.
I tried the following:
string oldPath = "\\new\new1\new2\";
string newPath = old.replace("\\", "\\\\");
My expected result is that newPath is as follows:
"\\new\\new1\\new2\\"
First of all, your oldPath is not a valid string in Java. It ends with \ which is a special character and it must be followed by something. Let's assume it should be \\ at the end.
Besides this, as #Jens mentioned in comments, \n is a new line sign, so java understands your string as \new(new_line)ew1(new_line)ew2\.
Now, if you want your result to be displayed as \\new\\new1\\new2\\ you need to use this
String newPath = old.replace("\\", "\\\\").replace("\n", "\\\\n");
Notice that the order of replace methods is important in that case.
That is because \n is interpreted as a new line. Escape one more time.
Anyways better, use java.nio.file.Path instead of String to work with files and direcory paths. Also, use System.getProperty("file.separator") to work with the file separator \ \ /.
On a unix based system, path separator is /:
/**
* Succeeds on Unix-based systems. On Windows, replace test Path and expected Path file separators
* with backslash(es).
*/
#Test
public void test() {
final Path oldPath = Paths.get("//new/new1/new2");
final String newPath = oldPath.toString().replace(System.getProperty("file.separator"),
System.getProperty("file.separator") + System.getProperty("file.separator"));
System.out.println(System.getProperty("file.separator"));
System.out.println(newPath);
assertEquals("//new//new1//new2", newPath);
}

find file upload path in jsp

Can any body explain this code? i am confused please guide me and explain this code easy wording in JSP language .Thanks
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("<h3>Uploaded Filename:</h3> "+fileName);
}
}
In java file path can be described by \\.
For example: String path = "D:\\folder1\\folder2\\filename.type"
lastIndexOf("\\") will return the last position value of \\ from your file name.
The variable file will be assigned the path from which the file is going to be uploaded in the java program from your disk.
The if and else blocks check the file path is correct and it assigned the variable path.
Finally write method uploads the file from specified path.
First refer documentation of methods - lastIndexOfand substring lastIndexOf & substring to understand what these methods do.
Also note that we use double slashes in code due to \ being escape character so \\ means single slash \
If you apply, lastIndexOf("\\") , you might get either value -1 or >=0 . -1 value would mean that \ is not present in that String and value >=0 means that it is present.
In this below if part, you simply determine if \ is there in fileName , if it is there - take only last portion and append with filePath so for a fileName with value like abc\test.txt you are extracting only \test.txt and appending to filePath.
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}
Then , in else part, we already know that \ is not present in so code is unnecessarily doing - fileName.lastIndexOf("\\")+1) - this will always be zero.
else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
So code can simply be written as ,
else{
file = new File( filePath +fileName)}
line - new File(....) creates a File object that is where stream contents get written to.
On SO, these kind of questions don't get answered but I answered since your profile says that you are a student.
Secondly, I can't comment if that code is correct or incorrect, I simply explained what that code is doing.

Filter the URL path of images (img src) to obtain the file name

Using JSOUP I parse an HTML page and I've found the image path, but now I need to obtain the image file name which is a part of the url path.
For example, this is the img src:
http://cdn-6.justdogbreeds.com/images/3.gif.pagespeed.ce.MVozFWTz66.gif
The file name is 3.gif.
What shall I use to obtain the name from the URL path? Perhaps regex?
I also have other url images:
http://cdn-1.justdogbreeds.com/images/**10.gif**.pagespeed.ce.gsOmm6tF7W.gif
http://cdn-4.justdogbreeds.com/images/**6.gif**.pagespeed.ce.KbjtJ32Zwx.gif
http://cdn-2.justdogbreeds.com/images/**8.gif**.pagespeed.ce.WAWhS-Qb82.gif
http://cdn-3.justdogbreeds.com/images/**7.gif**.pagespeed.ce.UKTkscU8uT.gif
Instead of regex you can use String.lastIndexOf() with String.substring().
String imgSrc = "http://cdn-1.justdogbreeds.com/images/10.gif.pagespeed.ce.gsOmm6tF7W.gif";
String imageName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
imageName = imageName.substring(0, imageName.indexOf(".", 3));
System.out.println(imageName); // prints out 10.gif
This finds the last occurrence of forward slash ( / ), after which the image name starts. The rest of the string is the full image name. You want only the 10.gif bit, so the rest of Line 2 finds the next period after the image name.
You can use a regex replacement to get the value you need:
String filename = imgsrc.replaceAll("http://[^/]*justdogbreeds.com/images/([^/]*?\\.gif).*", "$1");
With the regex we match the whole URL, and capture the text right after the images/ and up to (including) the first .gif. The ([^/]*?\\.gif) matches 0 or more characters other than / as few as possible, and then .gif. If you have other extensions, you may either enumerate them in an alternation group (like ([^/]*?\\.(?:gif|jpe?g|png)), or use a more generic pattern [^.]+ (1 or more characters other than .):
String filename = imgsrc.replaceAll("http://[^/]*justdogbreeds.com/images/([^/]*?\\.[^.]+).*", "$1");
See IDEONE demo
String imgsrc = "http://cdn-1.justdogbreeds.com/images/10.gif.pagespeed.ce.gsOmm6tF7W.gif";
String filename = imgsrc.replaceAll("http://[^/]*justdogbreeds.com/images/([^/]*?\\.gif).*", "$1");
System.out.println(filename);

java regex - matching part of string stored in variable

I need to extract up to the directory a file is in, in the folder path. To do so, I created a simple regex. Here is an example path \\myvdi\Prod\2014\10\LTCG\LTCG_v2306_03_07_2014_1226.pfd
The regex below will find exactly what I need, but my problem is storing it into a variable. This is what I have below. It fails at the string array
String[] temp = targetFile.split("\\.*\\");
folder = temp[0];
Suggestions?
Thanks!
Edit
The exception being thrown is: java.util.regex.PatternSyntaxException: Unexpected internal error near index 4
If your path is valid within your file system, I would recommend not using regex and using a File object instead:
String path = "\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";
File file = new File(path);
System.out.println(file.getParent());
Output
\\myvdi\\Prod\\2014\\10\\LTCG\\
Simply, you need:
String path = "\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";
String dir = path.substring(0, path.lastIndexOf("\\") + 1);
You should use Pattern & Matchers which are much more powerful; from your description I'm not sure if you want to get the whole folder path, but if it is, here is a solution:
String s = "\\\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";
Pattern p = Pattern.compile("^(\\\\+[a-zA-Z0-9_-]+\\\\+([a-zA-Z0-9_-]+\\\\+)+).+$");
Matcher m = p.matcher(s);
if(m.matches()){
System.out.println(m.group(m.groupCount()-1));
}

Search for a matching string through more then one files in Java

I am attmpting to search through more then one text files in java for a matching random string ( given from the user ). I got myself a loop which loops throug filenames in the current directory in the project but i can't figure out how to open the files and check if i have a match somewhere int them. Here is the code that i have written to loop through the filenames.
String path = "."; //current directory
java.io.File folder = new java.io.File( path );
java.io.File[] fileList = folder.listFiles();
for( int i = 0; i < fileList.length; i++ ) {
// I should add code for searching int the files probably here
}
My research got me to some code for searching matches but in only one file and it looks like this:
final Scanner scanner = new Scanner(FileName);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains("Address")) {
// a match!
System.out.println("I found " + CurrClient.getClientName()
+ " in file " +FileName+"txt");
break;
}
}
But it works only with one file or it seems to me like this.
Can you please give me a push? :)
Replace FileName with fileList[i] and your should be on your way.
By the way, you must remember to close the scanner in the end of each iteration of the loop, by calling scanner.close(). See more the examples in the documentation

Categories

Resources