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
Related
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.
I want to create a temporary file (that goes away when the application closes) with a specific name. I'm using this code:
f = File.createTempFile("tmp", ".txt", new File("D:/"));
This creates something like D:\tmp4501156806082176909.txt. I want just D:\tmp.txt. How can I do this?
In this case, don't use createTempFile. The point of createTempFile is to generate the "garbage" name in order to avoid name colisions.
You should use File.createNewFile() or simply write to the file. Whichever is more appropriate for your use case. You can then call File.deleteOnExit() to get the VM to look after cleaning up the file.
If you want to create just tmp.txt, then just create the file using createNewFile(), instead of createTempFile(). createTempFile is used to create temporary files that should not have the same name when created over and over.
Also have a look at this post which shows a very simple way to create files.
Taken the post mentioned above:
String path = "C:"+File.separator+"hello"+File.separator+"hi.txt";
//(use relative path for Unix systems)
File f = new File(path);
//(works for both Windows and Linux)
f.mkdirs();
f.createNewFile();
try regex
fileName = fileName.replaceAll("\\d", "");
I'm trying to set the system property "java.security.policy" programmatically.
It works, as long as the path to the security policy file has no spaces.
File myFileReference = new File("C:\folder_name\security.policy")
System.setProperty("java.security.policy", myFileReference.getAbsolutePath());
System.setSecurityManager(new RMISecurityManager());
If there are spaces int the file path, they get escaped with a %20, like this
"C:\folder%20name\security.policy".
The code above executes fine, but then all security checks fail. I assume setProperty doesn't really find the file.
On Windows, writing the file name without that escaping for spaces works.
System.setProperty("java.security.policy", "C:\\some folder\\wideopen.policy");
So, the problem seems to be that %20 space escaping. I could replace it using a regex, but maybe that would make it work just on Windows, and fails somewhere else.
Also, I don't want to hard-code the file path like that.
I looked at the Java doc for a File function that returns a "System.setProperty" compatible path name that works on any platform. I also tried things like toURI().toString(), to no avail.
Is there an elegant way to get a working file path String from a File reference in 1 line of code?
EDIT:
This was simplified code, I construct the file like this
URL policyURL = Class.class.getResource("/sub local folder/wideopen.policy");
new File(policyURL.getFile())
I needed a relative path, so I used that little getResource trick, which happens to return an URL, with the nasty %20 escapings.
I can use an URLDecoder to strip them away now that I know what the problem is.
But is there a less error prone way?
I solved using the URLDecoder class. Here is a complete example of what I was trying to do, and the solution that made it work.
//here is the trick
URL policyFileURL = Class.class.getResource("/server/model/easy.policy");
String policyFilePath = "";
try {
policyFilePath = URLDecoder.decode(policyFileURL.getFile(), "UTF-8");
}
catch (UnsupportedEncodingException e) {}
//here what I wanted to do (now it works)
server.activate(port, new File(policyFilePath));
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 'm trying to create new file in windows 7 using
file.createNewFile()
but the file is not created and I got the following exception
Message:
The system cannot find the path specified
Stack Trace:
[java.io.IOException: The system cannot find the path specified,
at java.io.WinNTFileSystem.createFileExclusively(Native Method),
at java.io.File.createNewFile(File.java:883),
at com.mercury.mtf.actions.file.CreateEmptyFileTask.execute(CreateEmptyFileTask.java:56),
at com.mercury.mtf.actions.file.CreateEmptyFileAction.execute(CreateEmptyFileAction.java:42),
at com.mercury.mtf.core.AbstractAction.run(AbstractAction.java:50),
at com.mercury.mtf.core.Unit.runUnitAction(Unit.java:347),
at com.mercury.mtf.core.Unit.executeUnitAction(Unit.java:176),
at com.mercury.mtf.core.Unit.run(Unit.java:121),
at com.mercury.mtf.core.execution.DefaultUnitExecutor.call(DefaultUnitExecutor.java:24),
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303),
at java.util.concurrent.FutureTask.run(FutureTask.java:138),
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98),
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207),
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886),
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908),
at java.lang.Thread.run(Thread.java:619)]
I'm sure that the path exists, but I realized that the folder marked as read only. I tried to remove the read only flag but I can't get this to work.
Make sure your path separator character is proper.. You can use single forward slash or double back slashes. For example,
File f = new File("C:\\Documents and Settings\\thandasoru\\My Documents\\temp.txt");
f.createNewFile();
If the file is temporary you can use this function and you can forget all permissions problems:
File.createTempFile("prefix", "suffix")
Use File newFile=new File(folderName+chipItems[i]); rather than using File newFile=new File(folderName+chipItems[i], "w");. That will be OK. Avoid File Mode when you like to give functionality like Unix touch command.