I have a absolute path coming from my JSP page to my servlet. I want to add extra "\" to access the location to my file.
String filePath=request.getParameter("file1");
/*
filePath= D:\work
*/
I want in format like "D:\\work" in my servlet so that I can access the files reside in work folder.
I tried using file.pathSeperator() and file.seperator() but did not get desired output.
filePath = filePath.replace("\\", "\\\\");
The real question is why you need this at all?
Related
I am making an HTTP Server in Java so that (on start) it finds all files in a directory (and it's sub-directories) and adds them to the server. But when getting the path of a file and trying to give it to HttpServer.createContext(), it throws a java.lang.IllegalArgumentException: Illegal value for path or protocol. (with the string argument, say "\folder/index.html"). To get this value, I used
file.getParent().substring(24) + "/" + file.getName()
I used substring because I had to exclude the folder the web server is in. The illegal character is the backslash. I have tried extending File to change separator and separatorChar, but that only created 2 new variables. While using String.replace() didn't seem to have any effect. Is there a different method than File.getParent or File.getPath that I can use, or is there a way to use String.replace that I am not seeing?
EDIT:
String.replace() seems to be the best answer... But I am not completely sure how to use it.
EDIT 2: For some reason the backslash isn't showing up, so I changed it.
You have to use the java System.getProperty.
Notice that, in this context, "file.separator" is a key which we are
using to get this property from current system executing the java VM.
Insteady of using a slash (/), you should choose a platform agnostic file separator, as an example it should be:
String separator = System.getProperty("file.separator");
System.out.println(separator);
// unix / , windows \
Have a look at Paths.get(...)
Try Paths.get(".") // current working directory.
Or tell it, on which path it should start:
Use System.getProperty("user.dir"), for current loged in user, home directory.
String pathStr = "/";
Path homeDir = Paths.get(System.getProperty("user.dir"))
Getting from the user directory into the data directory: homeDir.get("data")
Path dataPath = Paths.get(System.getProperty("user.dir"));
File dataFile = dataPath.toFile();
Now use operations on dataFile, to check what files and directories there are, on that location of the file system.
I have a little problem with Struts 2 when I try to get the context path :
ServletActionContext.getServletContext().getRealPath("\\WebContent\\resources\\img\\");
I got this path:
C:\Users\killian\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SiteWebAdministrable\WebContent\resources\imgicone.jpg
Why the exact source path ?
Because i need to upload and save images for an admin website to control background and without the actual path i cannot save images in the resources path...
So i save the path with the name and extension in the database (no problem), and i need to save the image in the resource directory (image problem...)
Can someone help me please ? Did i forgot something ?
This question is the answer ?
How do you get the project path in Struts 2?
servletContext.getServletContext().getRealPath("/resources/img/name_of_image.png")
So, passing the "/" to getRealPath() would return you the absolute disk file system path of the /web folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/demo.war/ which you should be able to further use in File or FileInputStream.
Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use
String absolutePathToIndexJSP = servletContext.getRealPath("/") + "demo.png";
instead of
String absolutePathToIndexJSP = servletContext.getRealPath("/demo.png");
getRealPath() is unportable; you'd better never use it
Use getRealPath() carefully.
If all you actually need is to get an InputStream of the web resource, better use ServletContext#getResourceAsStream() instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream of index.jsp, then do not do:
InputStream input = new FileInputStream(servletContext.getRealPath("/demo.png")); // Wrong!
But instead do:
InputStream input = servletContext.getResourceAsStream("/demo.png"); // Right!
Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.
Set<String> resourcePaths = servletContext.getResourcePaths("/");
I have tried to read a file from controller class with this code
ReadFile readFile = new ReadFile();
String text = readFile.readFile("\resources\testing.txt");
renderRequest.setAttribute("text", text);
I have fetched it from view.jsp as
<%
String content = (String)request.getAttribute("text");
%>
But I am getting file not found exception. What is the way to get file content.
In a Java string, \ starts an escape sequence and "\r" and "\t" are escaped characters. For example "\t" is a string with the tab character. If you literally need \t in a string, you'll have to escape the backslash
doSomething("\\resources\\testing.txt");
or just eliminate the hassle: Java operates well when you use the forward slash as directory separator
doSomething("/resources/testing.txt");
Note that this refers to a file in the root directory of whatever drive the current path is on, it might be C:\resources\testing.txt or D:\resources\testing.txt - unless your ReadFile implementation manipulates the path somehow (which I leave up to your judgement). You can test this independent of Liferay, just in a command line application. The exception gets thrown way before your jsp gets displayed (I've changed the tags to flag the relevance)
This is pure Java, completely independent of Liferay.
The problem is with your relative path of resources file (testing.txt), that needs to be absolute. And to create absolute path, first you would require, portletContext which you can get from request, as following:
MVC Portlet:
PortletContext portletContext = request.getPortletSession().getPortletContext();
Where request is either renderRequest / actionRequest object. While in JSF, you can get request from externalContext, as following:
JSF Portlet:
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
PortletRequest request = (PortletRequest) externalContext.getRequest();
PortletContext portletContext = request.getPortletSession().getPortletContext();
Also, as suggested by Olaf Kock, if you use \, you would require to escape it, otherwise use /. I prefer to use File.separator, as it returns slash as per OS (I think!).
String relativeFilePath = File.separator + "resources" + File.separator + "testing.txt";
Now, you can get absolute path using portletContext as,
String absoluteFilePath = portletContext.getRealPath(relativeFilePath);
And then, rest of your code goes, as:
ReadFile readFile = new ReadFile();
String text = readFile.readFile(absoluteFilePath);
renderRequest.setAttribute("text", text);
Since you're getting a FileNotFoundException, Are you sure you're pointing to the proper file route? Have you tried with the absolute path? What SO are you using? Because maybe the file separators ("\") are the cause of your problem.
HIH.
Regards.
Path name is : /storage/emulated/0/Xender/video/MyVideo.mp4
I am able to get last file name [MyVideo.mp4] from path using
String path="/storage/emulated/0/Xender/video/MyVideo.mp4";
String filename=path.substring(path.lastIndexOf("/")+1);
https://stackoverflow.com/a/26570321/5035015
Now i want to extract path [/storage/emulated/0/Xender/video] from this path.
I have one use of this path in my code so that i want to do this like this.
How can i do this?
Any help will be appreciated.
new File(path).getParentFile().getName() should work.
With regards to your current code, don't implement your own path parser. Use File.
Also note that this has nothing to do with Android specifically; this is a general Java question.
I am trying to read xml and txt file using relative path,
I tried getServletContext().getContextPath();
but it gets the path in a wrong way
for example
My file path is :
D:\dev\workspace\Simulater\src\resources\Map.xml
Now when I apply,
System.out.println(getServletContext().getContextPath());
I get as an output:
/Simulater
and when i apply :
File myTestFile= new File(Api.CONTEXT_PATH+fileName);
String path = myTestFile.getAbsoluteFile().toString();
System.out.println(path);
i get D:\Simulater\src\resources\Map.xml
an it is a wrong path since it dose not contains
:\dev\workspace\
it seams like java takes the project name and add the driver that contains it
so dose any one can provide any help to get the right path
thanx
use getServletContext().getRealPath("/") to get full path D:\dev\workspace\Simulater\src\resources\ then you can read file by giving this full path and file name.
To read a file you nead to open an InputStream, as your file is in your classpath you can open the stream with the following statement :
InputStream is = this.getClass().getResourceAsStream("/Map.xml");