JFileChooser / FileWriter doesn't let me save in root of C: disk - java

I'm playing around and I made a notepad-like app using swing. Everything is working properly so far, except it's not letting me save the text file directly on C:/. On any other disk, and INCLUDING the root of the D: drive, or in folders of the C:/ disk it works like a charm. Why is this happening?
This is my code:
file_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser Chooser = new JFileChooser();
File DefaultDirectory = new File("C:/");
File Path;
int Checker;
FileFilter text_filter = new FileNameExtensionFilter(
"Text File (*txt)", "txt");
FileFilter another_filter = new FileNameExtensionFilter(
"Debug Filter (*boyan)", "boyan");
//
Chooser.setCurrentDirectory(DefaultDirectory);
Chooser.setDialogTitle("Save a file");
Chooser.addChoosableFileFilter(text_filter);
Chooser.addChoosableFileFilter(another_filter);
Chooser.setFileFilter(text_filter);
Checker = Chooser.showSaveDialog(null);
//
if (Checker == JFileChooser.APPROVE_OPTION) {
Path = Chooser.getSelectedFile();
System.out.println(Path.getAbsolutePath());
;// Just for
// debugging.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(Path
.getAbsolutePath()));
String[] myString = textArea.getText().split("\\n");
for (int i = 0; i < textArea.getLineCount(); i++) {
writer.append(myString[i]);
writer.newLine(); // SO IT CAN PRESERVE NEW LINES
// (APPEND AND SPLIT ARE ALSO
// THERE
// BECAUSE OF THAT)
writer.flush();
}
JOptionPane.showMessageDialog(null, "File saved.", "",
JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
Thanks a lot in advance!

Usually, one does not have write permissions in C:\.
Start the app as a privileged user
One should not do that, as it is not intended by OS design. Changing permissions on C:\, or the system drive respectively, is a no-go.
Save into a sub-directory of System.getProperty("user.home"); (way to go)
The user home could also be a network folder with nighly backup in a domain network, for example. Especially for remote sessions (RDP, Citrix), this is often the case.
If you absolutely need to install a static file outside of the users folders, do it once, with an installer, configured to raise privileges (UAC).

Related

JFileChooser.SetCurrentDirectory not working

I have a JFileChooser and I want to set the directory it opens using some information stored in a .txt file (I'm using a .txt file to persist the desired location between sessions). I can get the file, read the data and set it to a string, but when I try to use that string to set the directory I want to open it doesn't work. My code is roughly something like this:
//buffer contains a byte[] for "/Users/user/Documents/Work/folderToOpen"
desiredPath = new String(buffer);
jFileChooser1.setCurrentDirectory(new java.io.File(desiredPath));
After stepping through this, however, the current directory is set to /Users/user.
If anyone has any ideas about what I'm doing wrong or a better way to accomplish this I'd love to hear it.
Thank you
private static String LAST_FOLDER_USED = null;
//Get the desired file path for user preferences
String pluginRoot = System.getProperty("user.dir") + File.separator.toString();
//Create a file using the desired file Path
File userPreferences = new File(pluginRoot + File.separator + "UserPreferences.txt");
//Get a file called UserPreferences.txt from target/classes to create an input stream
String fileName = "UserPreferences.txt";
InputStream readInFile = getClass().getResourceAsStream(fileName);{
//Convert input stream to read from the desired file in the plug-in root ("filePath" Created Above)
try{
readInFile = new FileInputStream(userPreferences);
}
catch (IOException e){
e.printStackTrace();
}}
//Read the readInFile into a byte[]
String desiredPathToOpenImage;
byte[] buffer = new byte[1000];
int i = 0;{
try {
while((i = readInFile.read(buffer)) !=-1){
System.out.println(new String(buffer));
i++;
}}
catch (IOException e) {
e.printStackTrace();
};
//Convert byte[] to string (This should be the path to the desired folder when selecting an image)
desiredPathToOpenImage = new String(buffer);
}
//Create a New File using the desired path
File desiredPath = new File(desiredPathToOpenImage + File.separator + "prefs.txt");
public SelectImage(Viewer parent, boolean modal) {
super(parent, modal);
initComponents();
int returnVal = jFileChooser1.showOpenDialog(parent);
// Sets up arrays for storing file information to be passed back to the viewer class.
String[] filePath = new String[jFileChooser1.getSelectedFiles().length];
String[] fileName = new String[jFileChooser1.getSelectedFiles().length];
String[] fileDir = new String[jFileChooser1.getSelectedFiles().length];
if (returnVal == JFileChooser.APPROVE_OPTION) {
// Cycles through the selected files and stores each piece accordingly
for (int i = 0; i < jFileChooser1.getSelectedFiles().length; i++) {
File file = jFileChooser1.getSelectedFiles()[i];
filePath[i] = file.getPath();
fileName[i] = file.getName();
fileDir[i] = file.getParent();
}
}
parent.setFilePath(filePath, fileName, fileDir);
}
private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jFileChooser1.setMultiSelectionEnabled(true);
//Checks folder_Path to see if a value is present. If value is present sets jFileChooser Directory to that value
if(desiredPathToOpenImage.contains(File.separator)){
//Create a File using the desired path for selecting images
//****Currently doesn't set the Directory correctly****//
jFileChooser1.setCurrentDirectory(desiredPath);
}
//If no value is present in LAST_FOLDER_USED sets jFileChooser Directory to desktop
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
//After file is selected sets value of LAST_FOLDER_USED to the absolute path of that file
LAST_FOLDER_USED = jFileChooser1.getCurrentDirectory().toString() + File.separator + "UserPreferences.txt";
try {
FileWriter fileWriter = new FileWriter(userPreferences);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jFileChooser1.getCurrentDirectory().toString());
OutputStream outPut = new FileOutputStream(pluginRoot + File.separator + "UserPreferences.txt");
outPut.write(LAST_FOLDER_USED.getBytes());
outPut.close();
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Error Writing to File" + desiredPathToOpenImage);
e.printStackTrace();
}
}
});
I think the directory passed as argument does not exist or is not accessible to the user you are logged in with judging from the javadoc of setCurrentDirectory():
If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.
Make sure all folders in the given path exist and are accessible to the logged user (on linux the 'executable' bit controls the accessibility of a directory). So if you see something like
-d x Documents
after executing
ls -l *
in a shell then the Documents directory is accessible.
Found a better way to accomplish my goal using Preferences instead of trying to create and access files to store the location.
Preferences prefs = Preferences.userNodeForPackage(this.getClass());
static String LAST_FOLDER_USED = "LAST_FOLDER_USED";
String folder_Location;
and then inside initComponents()
if(LAST_FOLDER_USED != null){
jFileChooser1.setCurrentDirectory(new File(prefs.get(LAST_FOLDER_USED, LAST_FOLDER_USED)));
}
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
folder_Location = jFileChooser1.getCurrentDirectory().toString();
prefs.put(LAST_FOLDER_USED, folder_Location);
//System.out.println(prefs.get(LAST_FOLDER_USED, folder_Location));
}
});

Deleting file inside JComboBox

I've got a JComboBox filled with some java.io.File objects. By selecting one of these files in the ComboBox, I want to delete it either from the ComboBox and Filesystem.
Code snippet:
deleteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure?", "Warning", dialogButton);
if (dialogResult == JOptionPane.YES_OPTION)
{
Path path = Paths.get(mailingLists.getSelectedItem().toString());
mailingLists.removeItem(mailingLists.getSelectedItem());
try
{
Files.delete(path);
JOptionPane.showMessageDialog(null, "File deleted!", "SUCCESS", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e1)
{
JOptionPane.showMessageDialog(null, e1.toString(), "ERROR", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
}
});
It gives this exception: java.nio.file.FileSystemException [...] file already in use this is because it's used by my application, then I thought first to remove it from the ComboBox and then delete it using Files.delete(path); but still have the exception.
What's wrong?
P.S.
Is the first time that I deal in this context so I guess if it's better to use File f = new File("path"); f.delete(); instead of Files.delete(path);.
EDIT: Provided more information about the JComboBox load.
Scratch:
LinkedList<File> listFolder = new LinkedList<File>();
listFolder.add(new File("mailinglists"));//<--- root folder
File[] stuffInFolder = listFolder.get(0).listFiles();
JComboBox<File> mailingLists = new JComboBox<File>(stuffInFolder);
Sounds like you need to close the file.
When you open a file the OS will prevent a file from being deleted until the connection to the file has been closed.
I would recommend, instead of JComboBox filled with some java.io.File objects use file names with path as String. And when you have to delete the file create an Object of File using the path and delete it.
Use Java.io.File.delete()
try
{
File f = new File(path);
if(f.delete())
JOptionPane.showMessageDialog(null, "File Deleted Succesfully!");
else
JOptionPane.showMessageDialog(null, "File couldn't be deleted!");
}
Solved!
I was using a "bugged" external library developed by a workmate. Its goal was to read a .properties file. Once readed, the file was still opened.
Fixed and everything works well now.

Saving file generated from Java Code to user defined location like download Functionality

I have a requirement where i have to save a file that i m generating using my java code and but as when i want to save it i want to let user decide where they want to save it.Like a download option that comes when we download a file from internet.I have tried using JFileChooser. But it does not work the way i want it to work.Can somebody please help.
Im creating the file like
try{
writer= new PrintWriter("F://map.txt", "UTF-8");
}catch(Exception e){
e.printStackTrace();
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
JFrame parentFrame = new JFrame();
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
Writing to a file
Note that this will overwrite the file if it exists, and it will not automatically prompt you for sh*t if it does. You have to check if it exists by yourself.
byte dataToWrite[] = // source
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(dataToWrite);
out.close();
In your case this would probably read out as
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(source);
out = new FileOutputStream(fileToSave.getPath());
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
Please note that this is untested code and I have no real routine with this stuff. You should google "java write file" or something like that if this proves to be erronous code :)

File not saved using JFileChooser in Java

Iam a java beginner.
I have written a simple program to write some contents to a file using showSaveDialoge() in JFileChooser. The code including below.
public static void main(String arg[]) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
try {
File file = new File("fileName.txt");
fc.setSelectedFile(file);
int r = fc.showSaveDialog(frame);
if(r == JFileChooser.APPROVE_OPTION)
{
FileWriter writer = new FileWriter(file);
writer.append("Data inside the file");
writer.flush();
writer.close();
}
else if(r == JFileChooser.CANCEL_OPTION) {
System.out.println("Do nothing for CANCEL");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "File could not be written, try again.");
}
}
the code gets executed and Save Dialogue box has come. But when I click SAVE button on Dialogue box, nothing had happening. The file has not saved in the selected location. What may be the reason.?
Thanks in advance.
What is hapenning is:
you create a File in your current location with name fileName.txt
File file = new File("fileName.txt"); //could be $HOME$/fileName.txt
User selects ProgramFiles/file.txt
but you uses on FileWritter file information, not what user chossed from FileChooser.
change
FileWriter writer = new FileWriter(file);
to
FileWriter writer = new FileWriter(chooser.getSelectedFile());
Try this:
FileWriter writer = new FileWriter(fc.getSelectedFile());
It should write to selected file from file chooser.
You were writing to fileName.txt which will be saved in current directory from which you run program.

Writing File object to another location

I have chosen file using
File file = fileChooser.getSelectedFile();
Now I want to write this file chosen by user to another location when user clicks save button. How to achieve that using swing?
To select the file you need something like ,
JFileChooser open = new JFileChooser();
open.showOpenDialog(this);
selected = open.getSelectedFile().getAbsolutePath(); //selected is a String
...and to save a copy ,
JFileChooser save = new JFileChooser();
save.showSaveDialog(this);
save.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
tosave = fileChooser.getSelectedFile().getAbsolutePath(); //tosave is a String
new CopyFile(selected,tosave);
...the copyFile class will be something like,
public class CopyFile {
public CopyFile(String srFile, String dtFile) {
try {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Also have a look at this question : How to save file using JFileChooser? #MightBeHelpfull
Swing will just give you the location/File object. You are going to have to write the new file yourself.
To copy the file, I will point you to this question: Standard concise way to copy a file in Java?
If you are using JDK 1.7 you can use the java.nio.file.Files class which offers several copy methods to copy a file to a given destiny.
read the file into a InputStream and then write it out to an OutputStream.

Categories