I'm using Apache libraries to edit DOCX file and I want user to choose dir where to save his file. It doesnt matter what folder to select it always thows an excetion and says "path (Access denied)", however, if I choose the directory in my code it works perfectly. Here's some of my code:
XWPFDocument doc = null;
try {
doc = new XWPFDocument(new ByteArrayInputStream(byteData));
} catch (IOException e) {
e.printStackTrace();
}
/* editing docx file somehow (a lot of useless code) */
Alert alert = new Alert(Alert.AlertType.INFORMATION);
DirectoryChooser dirChooser = new DirectoryChooser();
dirChooser.setTitle("Choose folder");
Stage stage = (Stage) (((Node) event.getSource()).getScene().getWindow());
File file = dirChooser.showDialog(stage);
if (file != null) {
try {
doc.write(new FileOutputStream(file.getAbsoluteFile()));
alert.setContentText("Saved to folder " + file.getAbsolutePath());
} catch (IOException e) {
alert.setContentText(e.getLocalizedMessage());
}
} else {
try {
doc.write(new FileOutputStream("C://output.docx"));
alert.setContentText("Saved to folder C:\\");
} catch (IOException e) {
alert.setContentText(e.getLocalizedMessage());
}
}
alert.showAndWait();
Please help me to figure out what I'm doing wrong :(
DirectoryChooser returns a File object which is either a directory or a null (if you did not choose one by pressing cancel or exit the dialog). So in order to save your file, you need to also append the file name to the absolute path of the directory you choose. You can do that by :
doc.write(new FileOutputStream(file.getAbsoluteFile()+"\\doc.docx"));
But this is platform dependent cause for windows it’s ‘\’ and for unix it’s ‘/’ so better use File.separator like :
doc.write(new FileOutputStream(file.getAbsoluteFile()+File.separator+"doc.docx"));
You can read more about the above here
Edit: As Fabian mentioned in the comments below you can use the File constructor, passing the folder ( the file you got from them DirectoryChooser ) and the new file name as parameters which makes the code far more readable :
new FileOutputStream(new File(file, "doc.docx"))
Related
So i was making a maven plugin, which main goal would be to generate extra resource inside of the final jar file, but i couldnt find how to actually put the file inside of the jar.
The closest i got was saving the file in the output directory, which doesnt really help my case, and most of the google search results gave me either documentation on how to use "Apache maven resource plugin" or "how to create maven plugins", neither of them having the information i seek =\
Update 1:
Tried saving the file to the target/classes, but the resulting file is empty (no idea why) and isnt copied to the final jar either way
File dir = new File(project.getBuild().getDirectory(),"classes");
if(dir.exists()){
File result = new File(dir,"AzimDP.json");
try {
getLog().info(gson.toJson(toSave));
gson.toJson(toSave, new FileWriter(result));
} catch (Exception e) {
getLog().warn(e);
}
}else{
getLog().warn("Unable to save file since target/classes doesnt exist");
}
Update 2 and working solution:
turns out i forgot to flush and close the FileWriter, and thus the file was empty. After i fixed that, everything works:
File dir = new File(project.getBuild().getDirectory(),"classes");
if(!dir.exists()) {
dir.mkdirs();
}
File result = new File(dir,"AzimDP.json");
try {
FileWriter writer = new FileWriter(result);
gson.toJson(toSave, writer);
writer.flush();
writer.close();
} catch (Exception e) {
getLog().warn(e);
}
In the end, the working solution based off #GyroGearless comment:
Gson gson = new Gson();
File dir = new File(project.getBuild().getDirectory(), "classes");
if(!dir.exists()) {
dir.mkdirs();
}
File result = new File(dir, "AzimDP.json");
try {
FileWriter writer = new FileWriter(result);
gson.toJson(toSave, writer);
writer.flush();
writer.close();
} catch (Exception e) {
getLog().warn(e);
}
where project is MavenProject and toSave is JsonArray.
Used in Maven 3 at LifecyclePhase "generate resources"
I'm trying to move myJar.jar from the update folder F:\Test Server\plugins\update to F:\Test Server\plugins.
I believe I'm messing up with the paths.
I have tried:
new File(PluginManager.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath());
//F:\Test%20Server\plugins\myPlugin.jar (just a test)
new File("update" + File.separator).listFiles(); //this however just produces null
File file = new File(PluginManager.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath()); //this gets the path where current running jar is
File[] directories = new File(String.valueOf(file))
.listFiles(File::isDirectory);
if (directories != null) {
for (File dir : directories)
System.out.println(dir.toString());
}
}
//this also produces null - I got this code from the internet
Finally, I've tried:
File theFile = new File("F:\\Test%20Server\\plugins\\update\\myJar.jar");
if (!(theFile.exists())) { //this is always the result
System.out.println("not found myJar.jar");
} else {
try {
Files.move(Paths.get("/update/myJar.jar"),
Paths.get("myJar.jar"),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
I expected that it would actually not keep saying "not found myJar.jar" but alas I think I'm doing a rookie mistake.
I figured out how to do this;
File a = new File("F:\\Test-Server\\plugins\\update\\myJar.jar");
a.renameTo(new File("F:\\Test-Server\\plugins\\" + a.getName()));
a.delete();
src
I have the following code
Process p = new ProcessBuilder("D:\\Encryption.exe", "D:\\Cat-hd-
wallpapers_remain_both2.jpg").start();
This code can run fine but instead of declaring "D:\Cat-hd-
wallpapers_remain_both2.jpg" this in my code I want to use file chooser for selecting file.
I use the following code but still not working.
imageUpload.setOnMouseClicked(event -> {
FileChooser fileChooser=new FileChooser();
fileChooser.setInitialDirectory(new File("c:\\"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("JPG Images","*.jpg"),
new FileChooser.ExtensionFilter("JPEG Images","*.jpeg"),
new FileChooser.ExtensionFilter("PNG Images","*.png"));
File file=fileChooser.showOpenDialog(null);
if (file!=null){
try {
imageUpload.setImage(new Image(file.toURI().toURL().toString()));
Process p = new ProcessBuilder("D:\\Encryption.exe",file.getAbsoluteFile().getAbsolutePath()).start();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(decriptImageController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
it throws the following error
CreateProcess error=2, The system cannot find the file specified
Can you please help me to find out the problem.Thanks in advanced.
The error "CreateProcess error=2, The system cannot find the file specified" refers to the executable, i.e. Encryption.exe, and has nothing to do with the JPEG file argument passed to it.
There must be something about your 2nd example that is different, but not shown in your question. Perhaps a subtle typo, e.g. Encyrption.exe etc...
So i'm working on a simple Windows Explorer replacement. I want to add the ability to create Folders and Files. For some reason, it only works when i'm in my root or c:/ folder, but as soon as it's somewhere else (for example C:\Program Files (x86)) it doesn't work. I either get a java.io.IOException: Access Denied when i create a File and when i try to create a folder, no Exception comes up, but no folder is created.
This is my code for a new file:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new file. \nDon't forget to add file type (.txt, .pdf).", null);
if(name == null){
}
else {
File newFile = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFile.createNewFile();
} catch (IOException Io) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "File creation failed with the following reason: \n" + Io);
}
}
This is my code for a new Folder:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new folder.", null);
if(name == null){
}
else {
File newFolder = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFolder.mkdir();
} catch (SecurityException Se) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "Folder creation failed with the following reason: \n" + Se);
}
}
I'm stuck right now and i have no idea what i'm doing wrong to get rid of the access denied error.
Short explenation of how this program works:
My program shows a list of all folders and files from a selected File.
That File is a field in the class JXploreFile called "currentFile", which behaves almost the same as a File.
When browsing through the folders, the currentFile is set to a new JXploreFile, containing the new folder you are in as File.
When creating a new folder/file, my program ask the path the user is currently browsing in with the method getPath().
Thanks for the help!
Image of my program:
Before you try to make any I/O operation just check if you have the permission
go to the parent directory (your case location)
then do something like
File f = new File(location);
if(f.canWrite()) {
/*your full folder creation code here */
} else {
}
try to put
String location ="c:\\user\<<youruser>>\\my documents"
or a folder with full perission to write
I have a simple updater for my application. In code i am downloading a new version, deleting old version and renaming new version to old.
It works fine on Linux. But doesn't work on Windows. There are no excepions or something else.
p.s. RemotePlayer.jar it is currently runned application.
UPDATED:
Doesn't work - it means that after file.delete() and file.renameTo(...) file still alive.
I use sun java 7. (because I use JavaFX).
p.s. Sorry for my English.
public void checkUpdate(){
new Thread(new Runnable() {
#Override
public void run() {
System.err.println("Start of checking for update.");
StringBuilder url = new StringBuilder();
url.append(NetworkManager.SERVER_URL).append("/torock/getlastversionsize");
File curJarFile = null;
File newJarFile = null;
try {
curJarFile = new File(new File(".").getCanonicalPath() + "/Player/RemotePlayer.jar");
newJarFile = new File(new File(".").getCanonicalPath() + "/Player/RemotePlayerTemp.jar");
if (newJarFile.exists()){
newJarFile.delete();
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
System.err.println("Cannot find curr Jar file");
return;
}
if (curJarFile.exists()){
setAccesToFile(curJarFile);
try {
String resp = NetworkManager.makeGetRequest(url.toString());
JSONObject jsresp = new JSONObject(resp);
if (jsresp.getString("st").equals("ok")){
if (jsresp.getInt("size") != curJarFile.length()){
System.out.println("New version available, downloading started.");
StringBuilder downloadURL = new StringBuilder();
downloadURL.append(NetworkManager.SERVER_URL).append("/torock/getlatestversion");
if (NetworkManager.downLoadFile(downloadURL.toString(), newJarFile)){
if (jsresp.getString("md5").equals(Tools.md5File(newJarFile))){
setAccesToFile(newJarFile);
System.err.println("Deleting old version. File = " + curJarFile.getCanonicalPath());
boolean b = false;
if (curJarFile.canWrite() && curJarFile.canRead()){
curJarFile.delete();
}else System.err.println("Cannot delete cur file, doesn't have permission");
System.err.println("Installing new version. new File = " + newJarFile.getCanonicalPath());
if (curJarFile.canWrite() && curJarFile.canRead()){
newJarFile.renameTo(curJarFile);
b = true;
}else System.err.println("Cannot rename new file, doesn't have permission");
System.err.println("last version has been installed. new File = " + newJarFile.getCanonicalPath());
if (b){
Platform.runLater(new Runnable() {
#Override
public void run() {
JOptionPane.showMessageDialog(null, String.format("Внимание, %s", "Установлена новая версия, перезапустите приложение" + "", "Внимание", JOptionPane.ERROR_MESSAGE));
}
});
}
}else System.err.println("Downloading file failed, md5 doesn't match.");
}
} else System.err.println("You use latest version of application");
}
}catch (Exception e){
e.printStackTrace();
System.err.println("Cannot check new version.");
}
}else {
System.err.println("Current jar file not found");
}
}
}).start();
}
private void setAccesToFile(File f){
f.setReadable(true, false);
f.setExecutable(true, false);
f.setWritable(true, false);
}
I found the solution to this problem. The problem of deletion occurred in my case because-:
File f1=new File("temp.txt");
RandomAccessFile raf=new RandomAccessFile(f1,"rw");
f1.delete();//The file will not get deleted because raf is open on the file to be deleted
But if I close RandomAccessFile before calling delete then I am able to delete the file.
File f1=new File("temp.txt");
RandomAccessFile raf=new RandomAccessFile(f1,"rw");
raf.close();
f1.delete();//Now the file will get deleted
So we must check before calling delete weather any object such as FileInputStream, RandomAccessFile is open on that file or not. If yes then we must close that object before calling delete on that file.
windows locks files that are currently in use. you cannot delete them. on windows, you cannot delete a jar file which your application is currently using.
Since you are using Java 7, try java.nio.file.Files.delete(file.toPath()), it'll throw exception if deletion fails.
There are several reasons:
Whether you have permissions to edit the file in windows.
The file is in use or not.
The path is right or not.
I don't know wich version of Java you are using.
I know when Java was sun property they publish that the Object File can't delete files correctly on windows plateform (sorry I don't find the reference no more).
The tricks you can do is to test the plateform directly. When you are on linux just use the classic File object.
On windows launch a command system to ask windows to delete the file you want.
Runtime.getRuntime().exec(String command);
I just want to make one comment. I learned that you can delete files in Java from eclipse if you run eclipse program as Administrator. I.e. when you right click on the IDE Icon (Eclipse or any other IDE) and select Run as Administrator, Windows lets you delete the file.
I hope this helps. It helped me.
Cordially,
Fernando