JFileChooser setCurrent directory to Homegroup or Network - java

I want that when my dialog is opened, then directly go to Homegroup. Thanks.
JFileChooser fc = null;
try {
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setCurrentDirectory(new File(new URI("file:C:\\" + "..\\Homegroup")));
fc.showOpenDialog(parent);
return fc.getSelectedFile().getAbsolutePath();
} catch (Exception e) {
return null;
}
This code is not working as I want. Thank you very much...

The problem is that you provide an invalid URI and thus get a URISyntaxException. Try something more clean and efficient that accesses an existing file, or learn
URI syntax:
fc.setCurrentDirectory(new File(System.getProperty("user.home")));

Related

How to make a file path compatible with an embedded database? (Apache Derby Embedded)

Recently I've been trying to use a JFileChooser to select where a database will be created; however, the problem I've run into is that the file path that I got from the JFileChooser has it has backslashes instead of forward slashes, and I think that this is what isn't allowing me to create the database. Here is my code, and attempt at solving the problem.
try {
// Try to connect to the database
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
databaseconnection = DriverManager.getConnection("jdbc:derby:"+formattedfolderpath+";");
databaseconnection.setAutoCommit(false);
currentdb = true;
} catch (SQLException EX) {
try {
// Create the DB if it doesn't exist yet
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
databaseconnection = DriverManager.getConnection("jdbc:derby:"+formattedfolderpath+";create=true");
databaseconnection.setAutoCommit(false);
currentdb = true;
} catch (SQLException EX2) {
//infoBox("OH MY LAWD", "Error");
}
and
JButton open = new JButton();
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("C:/Users/1jenningst/Desktop"));
fc.setDialogTitle("PDF Manager");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fc.showOpenDialog(open) == JFileChooser.APPROVE_OPTION){
//
}
String folderpath = fc.getSelectedFile().getAbsolutePath();
try{
formattedfolderpath = new BufferedReader(new FileReader(folderpath));
} catch (Exception e){
//
}
selecting();
}
Anyone have any ideas on how I could use a variable to complete the file path using a JFileChooser?
Thanks,
Michael
Ok,
I just needed to add two backslashes to the file path, instead of one:
C\users\missouri\desktop\123
becomes
C\\users\\missouri\\desktop\\123
Hope this helps,
Trevor

Backup a mysql [xampp] database in java

So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.
...
String path = null;
String filename;
//choose where to backup
private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());
try {
File f = fc.getSelectedFile();
path = f.getAbsolutePath();
path = path.replace('\\', '/');
path = path+"_"+date+".sql";
jTextField1.setText(path);
} catch (Exception e) {
e.printStackTrace();
}
}
//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
Process p = null;
try{
Runtime runtime = Runtime.getRuntime();
p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);
int processComplete = p.waitFor();
if (processComplete==0) {
jLabel1.setText("Backup Created Success!");
} else {
jLabel1.setText("Can't create backup.");
}
} catch (Exception e) {
}
}
You use a try-catch block in the jButtonBackUpActionPerformed, but the catch statement is empty. Therefore, if an exception is raised for whatever reason, no file would be written and you would get no output. You can try to use e.printStackTrace() like in the catch statement of the other button for debugging.
I found the underlying problem, thanks to stan. It was a typo problem, instead of "mysql", I have put "mysq" thank you guys!
java.io.IOException: Cannot run program "C:/xampp/mysq/bin/mysqldump.exe": CreateProcess error=2, The system cannot find the file specified
this will run any shell script on Linux server. Test it on windows ... shoud work too
public static int executeExternalScript(String path) throws InterruptedException, IOException {
ProcessBuilder procBuilder = new ProcessBuilder(path);
procBuilder.redirectErrorStream(true);
Process process = procBuilder.start();
BufferedReader brStdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = brStdout.readLine()) != null) { logger.info(line); }
int exitVal = process.waitFor();
brStdout.close();
return exitVal;}

How to save file.txt with JFileChooser?

I am developing notepad project, would like know how do for save a file.txt, my problem is, I keep the file opening JFileChooser, after selected the local where save intend, but after if save again will open JFileChoose again. I want save. Not save as.
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
PrintStream fileOut = null;
try {
File file = fc.getSelectedFile();
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (FileNotFoundException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
fileOut.close();
}
Change you work flow.
Basically, when you first save the file, you need to keep a reference to the File to which you saved to...
public class ... {
private File currentFile;
Now, when you go to save the file, you need to check if the currentFile is null or not. It it is null, you ask the user to select a file, otherwise, you can go ahead and try and save the file...
if (currentFile == null) {
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
}
}
// Used to make sure that the user didn't cancel the JFileChooser
if (currentFile != null) {
PrintStream fileOut = null;
try {
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (IOException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileOut.close();
} catch (IOException exp) {
}
}
If you want a save as an alternate to a save as, have the program store a File object referencing the currently opened file's path so the program is always aware of what it's editing, then just write to the programs file variable

How to read a file using jFileChooser after click of a button?

I want to read a file using jFileChooser. jFileChooser will come up after press of a button (say jbutton1ChooseFile) and select the required file. After the selection is complete, another button (say jbutton2) will be used to read the contents of the file which has just been selected by the user. So on clicking on jbutton2, selected file will be read.
I am posting few lines of code so that it would be easy to understand what I mean to say:
private void jButton1ChooseFileChooseFileActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser loadFile= new JFileChooser();
loadFile.setApproveButtonText("Select File");
loadFile.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter f1 = new FileNameExtensionFilter("Text Files", "txt", "text","rtf","doc","docx");
loadFile.setFileFilter(f1);
switch (loadFile.showOpenDialog(EncDecApp.this))
{
case JFileChooser.APPROVE_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Selection Successfull!",
"Attention!",
JOptionPane.OK_OPTION);
jButton1ChooseFile.setText("File Chosen");
jLabelChooseFile.setText(String.valueOf(loadFile.getSelectedFile()).substring(0,30)+"...");
fileSelect=true;
break;
case JFileChooser.CANCEL_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "No file chosen",
"Attention!",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
break;
case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Error",
"Choosing File",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
}
loadFile.setVisible(true);
}
Upto this it's working perfectly.
Now, the code for jButton2 is as follows:
private void jButton2EncryptEncryptActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Charset charset=Charset.forName("UTF-8");
int returnVal=loadFile.showOpenDialog(jLabel1);
if(returnVal==loadFile.APPROVE_OPTION)
{
File filePath = loadFile.getSelectedFile();
try{
BufferedReader in = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
jTextArea1.append(line + "\n");
}
in.close();
}
catch(IOException ex)
{
System.err.println("Open plaintext error: "+ex);
}
}
}
Any help will be highly appreciated.
At first glance the problem appears to be that you are using a local variable for the JFileChooser. That is to say, you have the line:
JFileChooser loadFile= new JFileChooser();
In your jButton1ChooseFileChooseFileActionPerformed function, and yet also try to refer to loadFile in your jButton2EncryptEncryptActionPerformed function.
In order to have the loadFile object available to both you need to have said loadFile object be a member of the class to which both functions belong.

Java read and write picture using MediaTracker

recently I wrote a code to get image (using jfileChooser) and then save it as new picture on hard Drive, and that worked. But when I try to use this code on other computers, or system it didn't work. The MediaTracker always contain a error but I can't display readable information about what going wrong, and I dont have idea how to fix this issue (but I don't won't to read again this source).
Thanks a lot for any ideas what can do wrong.
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new File("C:\\"));
jfc.showOpenDialog(null);
File sf = jfc.getSelectedFile();
if( sf==null )
return false;
String iconName = sf.getAbsolutePath();
URL imgUrl = null;
try
{
imgUrl = new URL("file:\\"+iconName);
}
catch(MalformedURLException murle){
//plujemy!
System.out.println(murle);
}
imageA = getToolkit().getImage(imgUrl);
MediaTracker mt = new MediaTracker(this);
try
{
mt.addImage(imageA,0);
mt.waitForAll();
}
catch (InterruptedException ie)
{
ie.printStackTrace(new PrintStream(System.out));
return false;
}
if(mt.isErrorAny()){
return false;
}else{
return true;
}
At a guess, absent a complete example, your call to waitForAll() is blocking the event dispatch thread. Note how the MediaTracker API example waits in a background thread. As an alternative, use SwingWorker to load the image(s), as shown here.

Categories