I have parsed a batch of XML Schema files using a DOMparser. I than added several annotations, which are essential for the application I am creating. I then want to write these new "preprocessed" files to a new location, and I get a FileNotFound exception (access denied).
Here's the snippet of code where I am writing the file:
Transformer tFormer = TransformerFactory.newInstance().newTransformer();
// Set output file to xml
tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
// Write the document back to the file
Source source = new DOMSource(document);
File preprFile = new File(newPath(xmlFile));
// The newPath function is a series of String operations that result in a new
relative path
try {
// Create file if it doesn't already exist;
preprFile.mkdirs();
preprFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
Result result = new StreamResult(preprFile);
tFormer.transform(source, result);
And the error I am getting is the following:
java.io.FileNotFoundException: absolutePathHere (Access is denied)
Which points to this line in the above snippet :
tFormer.transform(source, result);
I'm using a Windows machine (read somewhere that that can be the source of this error), and I've already tried turning UAC off, but no success.
I was thinking maybe the createNewFile() method doesn't release the file after it's been made, but was unable to find more information about that.
Here's hoping StackOverflow can come to my rescue once again.
It's probably running under a user account that doesn't have the rights to that directory.
You said "The directory is created, and it appears the file is created as a directory as well". So I think it creates directory named 'wsreportkbo_messages.xsd'
It gives you error may be because you are trying to read directory. You can list files in directories using listFiles().
You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders.
I found the solution:
File preprFile = new File(directory1/directory2/directory3/file.xsd);
File directory = new File(directory1/directory2/directory3/);
try {
// Create file if it doesn't already exist;
directory.mkdirs();
preprFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
Thanks for the help.
Related
I need to use a file in my application. If i upload the file to Data/Data/APP/files then it is added with -rw-rw-rw permissions which i can then use in my application. If i programatically write the file to getFilesDir() the exact same directory, i can see the 2 exact files in the same directory, however the programatically saved file has permissions -rw------- i cannot then access the file in my app using getfilesDir().
this is how the file is saved:
public void writeFileOnInternalStorage(Context mcoContext,String sFileName, String sBody){
File file = new File(getApplicationContext().getFilesDir(), "");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
How can i get the correct permissions to use the file. It may well not be a permissions issue it maybe the way i am saving the file? It is a .graphml extension file.
What do you mean by cannot access your file?
Take a look at this documentation (https://developer.android.com/training/data-storage), you don't need permission to access (read and write) files inside App-Specific Directory.
Edit:
I'm assuming that you already stored the file to the disk.
Please note that to read and write files inside App-Specific Directory doesn't require permission. You can read it using this simple code.
public File readFile(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
// do other stuff, like checking if the file exist, etc.
return file;
}
It doesn't matter what file extension it is, as long as the file exists, you will get it.
Actually there are so many articles that already cover this topic, please take a look to understand this topic better.
I've recently inherited a Java API and am having trouble with file uploads. Unfortunately, Java isn't a language I have much experience in so I'm a bit stumped by this.
The MultiPartFile is being received ok, and I can find the file in the temp directory, but when I try to use File.transferTo() to create the final file I just get the below error;
java.nio.file.NoSuchFileException: C:\Users\myUser\AppData\Local\Temp\undertow3706399294849267898upload -> S:\Dev\PolicyData\Temp.xlsx
As I mentioned the temp undertow file exists, and the directory on the S drive also exist, (but there's no Temp.xlsx as my understanding is this should be created by transferTo()). Any solutions I've found to this problem so far are resolved using absolute file paths.
This is a simplified version of the code but the error remains the same.
SpringBoot framework is "1.5.3.RELEASE", running Java 1.8.0_131
ResponseEntity handleFileUpload(#RequestPart(name = "file") MultipartFile file, #PathVariable Long stageFileTypeId) {
if (!file.isEmpty()) {
try {
String filePath = "S:\\Dev\\PolicyData\\Temp.xlsx";
log.info("Upload Path = {}", filePath);
File dest = new File(filePath);
file.transferTo(dest);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(filePath));
}
catch (Exception ex) {
log.error("An error has occurred uploading the file", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
else {
log.error("An error has occurred, no file was received");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
If you need any more information please let me know.
Thanks,
Neil
The API for MultipartFile is a bit tricky. The transferTo(File) method javadoc states that (bold are mine):
This may either move the file in the filesystem, copy the file in the
filesystem, or save memory-held contents to the destination file. If
the destination file already exists, it will be deleted first.
If the target file has been moved in the filesystem, this operation
cannot be invoked again afterwards. Therefore, call this method just
once in order to work with any storage mechanism.
It seems that the Undertow implementantion already called it to move the in-memory uploaded file to "C:\Users\myUser\AppData\Loca\Temp\undertow3706399294849267898upload" so another transferTo is failing.
I came across the same problem using javax.servlet.http.Part in a Wildfly containter with Undertow.
If you are using Spring framework >= 5.1, you could try the Multipart.transferTo(Path) method, using dest.toPath()
Or you can copy from the inputStream, with something like this:
try (InputStream is = multipartFile.getInputStream()) {
Files.copy(is, dest.toPath());
}
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
Here is my code to copy a war file to another using TrueZIP.
TFile srcFile = new TFile(sourceFilePath);
TFile destFile = new TFile(destFilePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
try {
srcFile.cp_rp(destFile);
TVFS.umount();
} catch (IOException e) {
e.printStackTrace();
}
For example, source file location:
I:\Code-Base\test.7.2.0\projects\test\main\branches\test.7.2.0_for_test\ui\portlets\dist\portlets.war\WEB-INF\server-config.wsdd
and destination location:
D:\deploy\work\237798_237980\web\deploy\prtlets.war\WEB-INF\server-config.wsdd
I've already checked that both paths exists, but I get an InputException error::
de.schlichtherle.truezip.io.InputException: de.schlichtherle.truezip.fs.FsReadOnlyArchiveFileSystemException: This is a read-only archive file system!
at de.schlichtherle.truezip.socket.IOSocket.copy(IOSocket.java:102)
at de.schlichtherle.truezip.file.TBIO.cp0(TBIO.java:221)
at de.schlichtherle.truezip.file.TBIO.cp_r0(TBIO.java:179)
at de.schlichtherle.truezip.file.TBIO.cp_r(TBIO.java:138)
at de.schlichtherle.truezip.file.TFile.cp_rp(TFile.java:3210)
at com.accela.work.WorkThread.run(WorkThread.java:110)
at com.accela.work.Worker.getUpgradePackageByVersion(Worker.java:162)
at com.accela.work.Main.generateUpgradePackage(Main.java:114)
at com.accela.work.Main.getUpgradePackageByVersion(Main.java:107)
at com.accela.work.Main.main(Main.java:75)
Caused by: de.schlichtherle.truezip.fs.FsReadOnlyArchiveFileSystemException: This is a read-only archive file system!
at de.schlichtherle.truezip.fs.FsReadOnlyArchiveFileSystem.mknod(FsReadOnlyArchiveFileSystem.java:54)
at de.schlichtherle.truezip.fs.FsBasicArchiveController$1Output.mknod(FsBasicArchiveController.java:273)
at de.schlichtherle.truezip.fs.FsBasicArchiveController$1Output.getLocalTarget(FsBasicArchiveController.java:220)
at de.schlichtherle.truezip.fs.FsBasicArchiveController$1Output.getLocalTarget(FsBasicArchiveController.java:217)
at de.schlichtherle.truezip.fs.FsContextController$Output.getLocalTarget(FsContextController.java:296)
at de.schlichtherle.truezip.fs.FsContextController$Output.getLocalTarget(FsContextController.java:280)
at de.schlichtherle.truezip.socket.DelegatingOutputSocket.getLocalTarget(DelegatingOutputSocket.java:47)
at de.schlichtherle.truezip.socket.DelegatingOutputSocket.getLocalTarget(DelegatingOutputSocket.java:21)
at de.schlichtherle.truezip.socket.DelegatingOutputSocket.getLocalTarget(DelegatingOutputSocket.java:47)
at de.schlichtherle.truezip.socket.DelegatingOutputSocket.getLocalTarget(DelegatingOutputSocket.java:21)
at de.schlichtherle.truezip.fs.FsSyncController$Output.getLocalTarget(FsSyncController.java:421)
at de.schlichtherle.truezip.fs.FsSyncController$Output.getLocalTarget(FsSyncController.java:408)
at de.schlichtherle.truezip.fs.FsLockController$Output$1GetLocalTarget.call(FsLockController.java:498)
at de.schlichtherle.truezip.fs.FsLockController$Output$1GetLocalTarget.call(FsLockController.java:495)
at de.schlichtherle.truezip.fs.FsLockController.locked(FsLockController.java:316)
at de.schlichtherle.truezip.fs.FsLockController.writeLocked(FsLockController.java:268)
at de.schlichtherle.truezip.fs.FsLockController$Output.getLocalTarget(FsLockController.java:501)
at de.schlichtherle.truezip.fs.FsLockController$Output.getLocalTarget(FsLockController.java:484)
at de.schlichtherle.truezip.socket.DelegatingOutputSocket.getLocalTarget(DelegatingOutputSocket.java:47)
at de.schlichtherle.truezip.socket.DelegatingOutputSocket.getLocalTarget(DelegatingOutputSocket.java:21)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Output$GetLocalTarget.call(FsFalsePositiveArchiveController.java:374)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Output$GetLocalTarget.call(FsFalsePositiveArchiveController.java:367)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$TryChild.call(FsFalsePositiveArchiveController.java:507)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController.call(FsFalsePositiveArchiveController.java:104)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Output.getLocalTarget(FsFalsePositiveArchiveController.java:364)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Output.getLocalTarget(FsFalsePositiveArchiveController.java:348)
at de.schlichtherle.truezip.socket.InputSocket.getPeerTarget(InputSocket.java:50)
at de.schlichtherle.truezip.fs.FsBasicArchiveController$1Input.getDelegate(FsBasicArchiveController.java:199)
at de.schlichtherle.truezip.socket.DelegatingInputSocket.getBoundSocket(DelegatingInputSocket.java:43)
at de.schlichtherle.truezip.socket.DelegatingInputSocket.newInputStream(DelegatingInputSocket.java:63)
at de.schlichtherle.truezip.fs.FsContextController$Input.newInputStream(FsContextController.java:273)
at de.schlichtherle.truezip.fs.FsResourceController$Input.newInputStream(FsResourceController.java:242)
at de.schlichtherle.truezip.socket.DelegatingInputSocket.newInputStream(DelegatingInputSocket.java:63)
at de.schlichtherle.truezip.fs.FsSyncController$Input.newInputStream(FsSyncController.java:378)
at de.schlichtherle.truezip.fs.FsLockController$Input$1NewInputStream.call(FsLockController.java:455)
at de.schlichtherle.truezip.fs.FsLockController$Input$1NewInputStream.call(FsLockController.java:452)
at de.schlichtherle.truezip.fs.FsLockController.locked(FsLockController.java:328)
at de.schlichtherle.truezip.fs.FsLockController.writeLocked(FsLockController.java:268)
at de.schlichtherle.truezip.fs.FsLockController$Input.newInputStream(FsLockController.java:459)
at de.schlichtherle.truezip.fs.FsFinalizeController$Input.newInputStream(FsFinalizeController.java:177)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Input$NewInputStream.call(FsFalsePositiveArchiveController.java:333)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Input$NewInputStream.call(FsFalsePositiveArchiveController.java:326)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$TryChild.call(FsFalsePositiveArchiveController.java:507)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController.call(FsFalsePositiveArchiveController.java:104)
at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Input.newInputStream(FsFalsePositiveArchiveController.java:323)
at de.schlichtherle.truezip.socket.IOSocket.copy(IOSocket.java:100)
... 9 more
TrueZIP does a simple test to check if the archive file is writable. If this test fails, the archive file system is set read-only as indicated by the exception.
In most cases, this is simply an issue with the access permissions. But Windows is particularly bitchy. For example, if there is another tool concurrently accessing the archive file (many Explorer plug-ins do this) then the file is effectively read-only, too.
So please stay away from the archive file (and best, its directory) while the operation is running.
You cannot do a replace on a read-only file, because you would have to delete it, i.e. write to it.
Make sure your destFile is writeable.
I'm writing a program where I'm trying to create a new text file in the current directory, and then write a string to it. However, when trying to create the file, this block of code:
//Create the output text file.
File outputText = new File(filePath.getParentFile() + "\\Decrypted.txt");
try
{
outputText.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
is giving me this error message:
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at code.Crypto.decrypt(Crypto.java:55)
at code.Crypto.main(Crypto.java:27)
Because of this I cannot write to the file because it naturally does not exist. What am I doing wrong here?
If you're working with the File class already, consider using its full potential instead of doing half the work on your own:
File outputText = new File(filePath.getParentFile(), "Decrypted.txt");
What's the value of filePath.getParentFile()? What operating system are you using? It might be a better idea to join both paths in a system-independent way, like this:
filePath.getParentFile() + File.separator + "Decrypted.txt"
It should be created as a sibling of the file pointed by filePath.
for example if
File filePath = new File("C:\\\\Test\\\\a.txt");
Then it should be created under Test dir.