Im developing a servlet, and I have to copy a file (*.doc) from a shared folder in other computer to my servlet webapp space, but I can't. The trouble is not writing on my Apache Server, instead of, Im expecting troubles copying the file from the remote folder (shared folder in a LAN). Any suggest or idea?
File inFile = new File( "\\\\192.168.2.103\\CompartidaMatias\\tablaEstudios.txt");
out.println("<p> AbsolutePath --> " + inFile.getAbsolutePath() + "</p>");
out.println("<p> Path --> " + inFile.getPath() + "</p>");
out.println("<p> Nombre --> " + inFile.getName() + "</p>");
out.println("<p> WEBAPP_ROOT --> " + WEBAPP_ROOT + "</p>");
File outFile = new File(WEBAPP_ROOT + "mydoc3a.txt");
if (inFile.exists())
out.println("<p>FILE FOUND</p>");
else
out.println("<p>FILE NOT FOUND</p>");
I get always FILE NOT FOUND :(
Thanks for your time buddies!! I hope it could be solved, but I have spent all my ideas. Thanks again!!
This is not how java.io.File works. It works on the local disk file system only, not on network resources.
Your best bet is to let your operating system platform create a local mapping (kind of a virtual disk) pointing to the network resource and, given you're on Windows, assign it a disk letter as well. Here's a Microsoft Windows 7 guide on the subject:
You just have to map \\192.168.2.103 to e.g. Z:\. Once done that, you should be able to locate the file as follows:
new File("Z:/CompartidaMatias/tablaEstudios.txt");
(note that / works as good as \\ and saves you from effort of escaping them)
Note that this problem has completely nothing to do with servlets. It's just a basic Java problem. You'd have exactly the same problem when executing this in a plain Java application with a main() method (which by the way allows for so much faster and easier testing than a servlet). Keep this in mind for your future questions.
try:
URL url = new URL( "file:///192.168.2.103//CompartidaMatias//tablaEstudios.txt" );
File inFile = new File( url.getFile() );
Related
I have been searching for a way to get a file object from a file, in the resources folder. I have read a lot of similar questions on this website but non fix my problem exactly.
Link already referred to
how-to-get-a-path-to-a-resource-in-a-java-jar-file
that got really close to answering my question:
String path = this.getClass().getClassLoader().getResource(<resourceFileName>)
.toExternalForm()
I am trying to have a resource file that I can write data into and then bring that file object to another part of my program, I know I can technically create a temp file that, I then write data into then pass it into a part of my program, the problem with this approach is that I think it can take a lot of system recourses, my program will need to create a lot of these temp files.
Is there any way, I can reuse one file in the resource folder? all I need is to get it's path (and it needs to work in a jar).I have tried this snipper of code i created for testing, i don't really know why it returns false, because in the ide it returns true.
public File getFile(String fileName) throws FileNotFoundException {
//Getting file from the resources folder
ClassLoader classLoader = getClass().getClassLoader();
URL fileUrl = classLoader.getResource(fileName);
if (fileUrl == null)
throw new FileNotFoundException("Cannot find file " + fileName);
System.out.println("before: " + fileUrl.toExternalForm());
final String result = fileUrl.toExternalForm()
.replace("jar:" , "")
.replace("file:" , "");
System.out.println("after: " + result);
return new File(result);
}
Output:
before: jar:file:/C:/Users/%myuser%/Downloads/Untitlecd.jar!/Recording.wav
after: /C:/Users/%myuser%/Downloads/Untitlecd.jar!/Recording.wav
false
i have been searching for a way to get a file object from a file in the resources folder.
This is flat out impossible. The resources folder is going to end up jarred into your distribution, and you can't edit jar files, they are read only (or at least, you should consider them so. Non-idiotic deployments will generally mark their own code files (which includes those jars) as read-only to the running process. Even if not, editing jar files is extremely heavy and not something you want to do. Even if you do, on windows, open files can't be edited/replaced like this without significant headaches).
The 'resources' folder simply isn't designed for files that are meant to be modified.
The usual strategy is to make a directory someplace (for example, the user's home dir, accessing via System.getProperty("user.home"), and then make/edit files within that dir. If you wish, you can put templates in your resources folder and use those to 'initialize' that dir hanging off the user's home dir with a skeleton version.
If you have a few ten thousand files to make, whatever process needs this needs to be adjusted to not need this. For example, by using a database (H2, perhaps, if you want to ship it with your java app and have it be as low impact as possible).
We are noticing unwanted behaviour with uploading files via xp:fileUpload control. sometimes users get files from other users uploaded.
the files are named the same but the content differes.
I was using:
File correctedFile = new File(tempFile.getParentFile() + File.separator + tempClientFile);
to create a file in Notes document from uploaded file.
I noticed in some other code from others the following was used:
File correctedFile = new File( serverFile.getParentFile().getAbsolutePath() + File.separator + fileName );
Can the lacking of absolutepath can be the cause of file switch?
Ofcourse we have never noticed the occurrence under Testing in our Test environment.
.getAbsolutePath() returns the full path whereas .toString() which is implicit used in your case returns just the abstract path.
Here is a description of the difference.
I use .getAbsolutePath() in my Domino backend code and never experienced the issue you describe.
So, I'm creating a game and need to create directories to store all the user's data and saves and whatnot. As you can see, I need to create a folder in the Application Data folder of the user called, "[WarDungeon]", and there, I will store other folders for such data like levels, the bin, sprites, etc.
I am not too interested in working with Mac OS and Linux as I want to get the %appdata% folder working with Windows to begin with.
Here's my code:
public FileManage() {
gamePath = System.getenv("APPDATA") + "[WarDungeon]";
gameLevelPath = System.getProperty("user.home") + "\\Local Settings\\ApplicationData\\[WarDungeon]\\level";
gameBinPath = System.getProperty("user.home") + "\\Local Settings\\ApplicationData\\[WarDungeon]\\bin";
File createDir1 = new File(gamePath);
createDir1.mkdir();
System.out.println("First test passed.");
if (createDir1.exists() == true) {
System.out.println("First directory created!");
}
}
How do I fix this?
Thanks in advance, :)
I realize that this question is two years old, but since this is the first result while googling "java store in appdata", I decided to add a correct answer for future googlers.
The question is tagged with Java, and the OP posted Java code, but the accepted answer is .NET (not Java).
Quoted directly from this answer:
System.getenv("APPDATA")
This will give the location to the user's AppData folder (in Windows). You can get a result similar to what the OP wanted by doing the following:
File characterFolder = new File(System.getenv("APPDATA") + "\\" + characterName);
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
I am on latest glassfish (3.1.2) - so no need for apache FileItem and no bugs with getPart(). I read that the best practice on uploading images is saving them on the file system (see here for instance). I am editing already existing code - smelly at that - so I had the idea to do :
Part p1 = request.getPart("file");
System.out.println("!!!!!P1 : " + p1);
Prints :
!!!!!P1 : File name=DSC03660.JPG,
StoreLocation=C:\_\glassfish3\glassfish\domains\domain1\generated\jsp\elkethe\upload_7cb06306_138b413999a__7ffa_00000000.tmp,
size=2589152bytes, isFormField=false, FieldName=file
newlines mine. In the code people are doing :
if (request.getParameter("crop") != null) {
// get path on the server
String outputpath = this.getServletContext().getRealPath(
"images/temp/" + session.getId() + ".jpg");
// store photo
InputStream is = p1.getInputStream();
createPhoto(is, outputpath);
session.setAttribute("photo_path", "images/temp/" + session.getId()
+ ".jpg");
response.sendRedirect("cropping");
return;
}
Where
private void createPhoto(InputStream is, String outputpath) {
FileOutputStream os = null;
try {
os = new FileOutputStream(outputpath);
// write bytes taken from uploaded file to target file
int ch = is.read();
while (ch != -1) {
os.write(ch);
ch = is.read();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
Helpers.close(os);
}
}
Now what happens is that the file is uploaded in the StoreLocation (???) on submitting the form so apparently all this p1.getInputStream() is for naught.
My questions are :
what is StoreLocation ? How tmp are those glassfish uploads ? Where are all those parameters set ? I did read BalusC' tutorial - but there is no mention of StoreLocation (google is not very helpful either).
What would be a more professional way of handling the situation - including keeping the photos outside the webroot - but using facilities glassfish provides (if it does provide) ?
Even p1 printing so nice escapes me (it does not seem to Override toString())
Interested in tips even in how should one rename the photos etc (is this sessionID thing Right ? - check also the time trick) :
if (request.getParameter("save") != null) {
long time = System.currentTimeMillis();
String path = "images/upload/" + session.getId() + time + ".jpg";
String outputpath = this.getServletContext().getRealPath(path);
// store photo
InputStream is = p1.getInputStream();
createPhoto(is, outputpath);
// etc
}
Good practice is to pick a path on the filesystem where photos will be uploaded. Often this path is programmed to be configurable via java system property (eg: by passing -Dcom.mycompany.uploadPath=/path/to/photos/dir system property on JVM arguments).
You can also use java system propeties to find environment specific path: user.dir, user.home etc. See System Properties on Java SE Tutorial. Or to use glassfish-relative path, see glassfish system properties.
Once you have reference to Part, it's just about doing file IO to copy the uploaded file into this upload path, eg:
Part part = // obtain part somehow..
String photoFileName = // build a file name somehow..
InputStream photoInputStream = part.getInputStream();
FileOutputStream photoOutputStream = new FileOutputStream(System.getProperty("com.mycompany.uploadPath") + File.separator + photoFileName);
IOUtils.copy(photoInputStream, photoOutputStream);
// close streams here...
Code above uses apache IOUtils for convenience but feel free to write your own copy method. You should also add exception handling method
What is StoreLocation ? How tmp are those glassfish uploads ? Where are all those parameters set ?
StoreLocation is just the the java.io.File object for the FileItem's
data's temporary location on the disk. Resides in javax.servlet.context.tempdir which defaults to %GLASSFISH_HOME%\domains\domain1\generated\jsp\webApp. Those uploads are as tmp as anything (The lifetime of the file is tied to the lifetime of the FileItem instance; the file will be deleted when the instance is garbage collected - from here). Haven't yet managed to change the value of javax.servlet.context.tempdir programmatically (comment please) - it is the tempdir property of the sun-web-app element of the sun-web.xml.
What would be a more professional way of handling the situation - including keeping the photos outside the webroot - but using facilities glassfish provides (if it does provide) ?
Well a more professional way is to Use Part.write() to move the file to the desired location. Due to glassfish implementation though you can't supply an absolute path to write - a chore. I asked here.
As to where to save the file : https://stackoverflow.com/a/18664715/281545
That is for saving the file - to serve it from a location outside the app you need to define "alternatedocroot" properties in the sun-web.xml (or glassfish-web.xml).
Even p1 printing so nice escapes me (it does not seem to Override toString())
Oh yes it does
Interested in tips even in how should one rename the photos etc (is this sessionID thing Right ? - check also the time trick)
No it is not - I tend towards File#createTempFile() - anyway this is a different question asked here
i am aware i am asking somethink that cannot be done without manually looping over the file system. But maybe someone have a better idea then mine.
i have a list of users and just one of them has in his own folder the file aaa.xml
from the linux shell of course if i type
vi /user/*/aaa.xml
i can open the file. I would like to use the same future in java but it seams not to Work
File designFile = new File("/user/*/aaa.xml");
solution would be to try to locate the file in each of the users directory but it seams not to nice. do you guys have a better idea??
cheers,
Ste
This might be related to what you are looking for. Hope it helps.
A FileSet package/class wanted for Java
Edit:
Then how about this?
How to find files that match a wildcard string in Java?
well.. seams not feasible because cannot work over different Operating systems.
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
String filePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("File path : " + filePath);