url = new java.net.URL() - java

url = new java.net.URL(s) doesn't work for me.
I have a string C:\apache-tomcat-6.0.29\webapps\XEPServlet\files\m1.fo and need to make a link and give it to my formatter for output, but malformed url recieved. It seems that it doesn't make my string to url.
I want also mention, that file m1.fo file is in files folder, in my webapp\product\, and I gave the full path to string like: getServletContext().getRealPath("files/m1.fo"). What I am doing wrong? How can I recieve the url link?

It is possible to get an URL from a file path with the java.io.File API :
String path = "C:\\apache-tomcat-6.0.29\\webapps\\XEPServlet\\files\\m1.fo";
File f = new File(path);
URL url = f.toURI().toURL();

Try: file:///C:/apache-tomcat-6.0.29/webapps/XEPServlet/files/m1.fo

It isn't preferable to write file:/// . Indeed it works on windows system,but in unix - there were problems.
Instead of using
myReq.put("xml", new String []{"file:" + System.getProperty("file.separator") +
getServletContext().getRealPath(DESTINATION_DIR_PATH) +
System.getProperty("file.separator") + xmlfile});
you can write
myReq.put("xml", new String [] {getUploadedFileURL (xmlfile)} );
, where
public String getUploadedFileURL(String filename) {
java.io.File filePath = new java.io.File(new
java.io.File(getServletContext().getRealPath(DESTINATION_DIR_PATH)),
filename);
return filePath.toURI().toURL().toString();

A file system path is not a URL. A URL is going to need a protocol prefix for one. To reference file system use "file:" in front of your path.

Related

Java: How to get path of a file when running JAR file

When I use relative path, I can run my Java program from Eclipse. But when I run it as a JAR file, the path doesn't work anymore. In my src/components/SettingsWindow.java I have:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./src/files/profile.ser"));
I get a FileNotFoundException.
My file directory looks like this:
file directory
What I've tried:
String filePath = this.getClass().getResource("/files/profile.ser").toString();
String filePath = this.getClass().getResource("/files/profile.ser").getPath();
String filePath = this.getClass().getResource("/files/profile.ser").getFile().toString();
And I'd just put filePath in new FileInputStream(filePath) but none of these work and I still get a FileNotFoundException. When I System.out.println(filePath) it says: files/profile.ser
I'm trying to get the path of src/files/profile.ser while I'm in src/components/SettingsWindow.java
You can get the URL to the class:
String path =
String.join("/", getClass().getName().split(Pattern.quote(".")))
+ ".class";
URL url = getClass().getResource("/" + path);
which will either yield "file:/path/to/package/class.class" or "jar:/path/to/jar.jar!/package/class.class". You either can work with the URL or use
JarFile jar =
((JarURLConnection) url.openConnection()).getJarFile();
and use jar.getName() to get the path to parse to get your installation directory.
To get the current JAR file path I use:
public static String getJarFilePath() throws FileNotFoundException {
String path = getClass().getResource(getClass().getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n"+path);
}
if(path.lastIndexOf("!")!=-1) path = path.substring(path.lastIndexOf("!/")+2, path.length());
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return path.substring(0, path.lastIndexOf('!')).replaceAll("%20", " ");
}

save file with different name in spring boot

I am uploading one file that is kind of multipart. I want this file to save with different name.
tried with renameTo method but did not work.
tried moveto but did not work
below is my code
here graphic is multipart file
String picName = graphic.getOriginalFilename();EN_LENGTH) + "." + graphic.getContentType();
Path dirLocation = Paths.get(dirPath);
String newName = CommonUtil.getToken(Constants.STANDRAD_TOKEN_LENGTH) + "." + graphic.getContentType();
try {
InputStream is = graphic.getInputStream();
Files.copy(is, dirLocation.resolve(picName), StandardCopyOption.REPLACE_EXISTING);
boolean a = new File(dirLocation+picName).renameTo(new File(dirLocation+newName));
for security reasons I want it to save with different name.
Solved the issue by correcting the filename. The file name which I was generating randomly was not correct. it had some slash etc.

extracting filename with extension form URL

Let's say I have the following string
http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png
What would be the best way to extract b84.png from it? My program will be getting a list of image URLs and I want to extract the file name with its extension from each URL.
I would recommend using URI to create a File like this:
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
URI uri = URI.create(url);
File f = new File(uri.getPath());
The uri.getPath() returns only the path portion of the url (i.e. removes the scheme, host, etc.) and produces this:
/photos/images/original/000/748/132/b84.png
You can then use the created File object to extract the file name from the full path:
String fileName = f.getName();
System.out.println(fileName);
Output of print statement would be:
b84.png
However if you are not at all concerned by the input format of the url(s) then the substring answers are more terse. I figured I would offer an alternative. Hope it helps.
Try,
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
String fileName = url.subString(url.lastIndexOf("/")+1);
String[] urlArray=yourUrlString.split("/");
String fileName=urlArray[urlArray.length-1];
I think, string lastIndexOf method is the best way to extract file name
String str = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
String result = str.substring(str.lastIndexOf('/')+1,str.length());
The method perfect for you
public String Name(String url){
url=url.replace('\\', '/');
return url.substring(url.lastIndexOf('/')+1,url.length());
}
this method returns any filename of any directory...whitout errors because convert the "\" to "/" so never will have problems with diferent directories
You can try this-
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png"
url = url.substring(url.lastIndexOf("."));
If you don't png instead of .png, just change the last line to this-
url = url.substring(url.lastIndexOf(".") + 1);

getServletContext().getRealPath("/") omitting forward slash (/)

I'm trying to upload a file from an HTML file input.
I am using Apache Commons FileUpload and the file uploads successfully. However, when I try storing the file path in my MySQL, it is storing it without file path code:
String uploadFolder = getServletContext().getRealPath("/");
String fileName = new File(item.getName()).getName();
filePath = uploadFolder+"/"+fileName;
File uploadedFile = new File(filePath);
This is how I'm trying to store the file.
sample filepath stored
C:UsersLashDesktopworkspace3.metadata.pluginsorg.eclipse.wst.server.core mp0wtpwebappsJavaECom/download doget.txt
I have no idea what this question is about, but the correct way to do the operations your posted code is doing is as follows:
File uploadFolder = new File(getServletContext().getRealPath("/"));
String fileName = new File(item.getName()).getName(); // not sure what's going on here
File uploadedFile = new File(uploadFolder, fileName);

Get file size in Java from relative path to file

How can I get file size in Java if I have a relative path to a file such as:
String s = "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with two diferent strings:
String[] separatedPath = s.split("/");
List<String> wordList = Arrays.asList(separatedPath);
String ret = "/" + wordList.get(1) + "/" + wordList.get(2) + "/" + wordList.get(3)+ "/" + wordList.get(4);
s = ret;
In this case s="/documents/19/21704/file2.pdf";
In second case s="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with:
File file1 = new File(s);
long filesize = file1.length();
and with:
String filePath = new File(s).toURI().getPath();
File file2 = new File(filePath);
long filesize2 = file1.length();
and also with (if the problem is in not providing full path):
String absolutePath = FileUtil.getAbsolutePath(file1);
File file3 = new File(absolutePath);
long filesize3 = file3.length();
byte[] bytes1=FileUtil.getBytes(file1);
byte[] bytes2=FileUtil.getBytes(file2);
byte[] bytes3=FileUtil.getBytes(file3);
I am always getting in debug that filesizes in all cases are 0.
Maybe is worth noticing that the three attributes of file1 and file2 and file3 are always:
filePath: which is always null;
path: "/documents/19/21704/liferay-portlet-development.pdf"
prefixLength: 1
Since I am also using Liferay I also tried their utility.
long compId = article.getCompanyId();
long contentLength = DLStoreUtil.getFileSize(compId, CompanyConstants.SYSTEM, s);
I also should notice that in my .xhtml view I can access the file with:
<a target="_blank"
href="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc">
file2.pdf
</a>
Pdf opens in a new window. So it is stored on my server.
What am I doing wrong here? That I cant get the file size from bean?
Any answer would be greatly appreciated.
What am I doing wrong here?
In Java, you can use the File.length() method to get the file size in bytes.
File file =new File("c:\\java_xml_logo.jpg");
if(file.exists()){
double bytes = file.length();
}
System.out.println("bytes : " + bytes);
The problem is that your "relative" path is expressed as an absolute path (begining with "/", which is read as FS root).
A relative file path should look like:
documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
./documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
Or, you could get your application root folder File and compose the absolute path:
File rootFolder =new File("path to your app root folder");
File myfile=new File(rootFolder, "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc");

Categories

Resources