I am trying to read a file in my Download folder (I have a mac system) using the below line of code:
PDDocument doc = PDDocument.load(new File("/Users/mohand/Downloads/1963_Automation_BigTurnip_290618.pdf"));
The problem is, the numeral "1963" will keep on changing but text "_Automation_BigTurnip_290618.pdf" will remain the same.
Can I use any regex that will pick up any file that has "_Automation_BigTurnip_290618.pdf" ?
I did this using :
File dir = new File("/Users/mohand/Downloads/");
File[] files = dir.listFiles((dir1, name) -> name.endsWith("Automation_BigTurnip_290618.pdf"));
No need for regex. Just use endsWith:
if (name.endsWith("_Automation_BigTurnip_290618.pdf"))
You could use a regular expression like this:
^(\d+)_Automation_BigTurnip_290618\.pdf$
This would match any file starting with at least one digit and ending in the pattern you specified.
Related
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
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
I am trying to filter files using FilenameFilter to grep files files in a directory.
% ls -1
DirFilter.class
DirList.class
DirList.java
doctors.txt
node.l
rels.l
I am trying to filter node.l and rels.l. Filter should succeed if and only if both files are present.
I tried my regex on debuggex.com and it seems to work as expected :
http://www.debuggex.com/embed/CZgVeUE2iWsNfRNG
my regex : (?s)node.l.?(?=(rels.l))
but when I run it through DirList.java filter it doesn't work..
% java DirList "(?s)node.l.?(?=(rels.l))"
<no-output>
Now I am using DirList.java from Thinking in Java
http://www.cs.odu.edu/~cs476/tijava2/c10/DirList.java
Any ideas?
DirList is evaluating your regex against each file name separately, not as a single \n delimited directory listing string as returned by ls. Your regex will never match under those conditions since it never sees more than one file name at a time.
FilenameFilter works for single file not for groups of files so regex will be applied only to that single file. Instead of regex try maybe this way:
take name of file
if it is node.l check if new File(currentDir+"/rels.l").exists().
if it is rels.l check if new File(currentDir+"/node.l").exists().
I am getting this error when I try to open a file:
java.io.FileNotFoundException: D:\Portable%20Programs\Android%20Development\workspace3\XXX-desktop\bin\World_X.fr (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
The file is existing in the directory but I am still getting this error. However when I copy the same file in the Eclipse workspace Project src folder, no such Exception is returned (though this method also creates the World_X.fr file in the bin folder).
What I am actually trying to do is get the absolute location of the .jar file through this:
fileLocation = new String(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
And then I am appending "World_X.fr" to the fileLocation string but this is not working. Please help me in this regard.
The preferred way to convert a file: URL into an actual File is this:
File file = new File(url.toURI());
This takes care of all checks and quoting/escaping.
Using getPath() instead will leave these odd bits up to you.
You need to unescape the %20 to spaces. e.g.:
fileLocation = new String(
Main.class.getProtectionDomain().getCodeSource().getLocation().getPath())
.replaceAll("%20", " ");
Here is the solution for that , this will work only after JDK1.5 ,
try { f = new File("somePath".toURI().getPath()); } catch(Exception e) {}
The confirmed solution is quite old and even though it works for this particular case it is far more convenient to use URLDecoder, because %20 is only one encoded character, but in your path there can be whole lot of different encoded characters.
fileLocation = URLDecoder.decode(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8");
Try leaving out the %20, and use normal spaces instead. Also, you're using backslashes, in your code if you're using backslashes make sure you escape them first.
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.