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
Related
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")));
Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..
I want to tell me How to save image to the mySQL after the user uploaded.
HINT : using NetBeans GUI Builder
This my code for choose image:
private void btnJFileChooserActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
image2.setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
e.printStackTrace();
}
}
This capture for Setter and Getter:
http://up07.s-oman.net/DVMGa.png
This capture for save button:
http://up07.s-oman.net/P2slSGkcj.png
Did you try saving is as a blob? Here's the link to solution on Stack Overflow: insert BLOB file from Local to DB
I am using a JFileChooser to allow the user to select a file and save the current game to it. The problem is that it allows just file selection, and it does not let create a file on the fly and save the game on it. Without creating a custom class, is there a way to allow this behavior in JFileChooser? I am using the file chooser to just select files, this is the code that I've written:
JFileChooser chooser= new JFileChooser();
chooser.setMultiSelectionEnabled(false);
chooser.setDialogTitle("Save the current game");
chooser.setFileFilter(new FileNameExtensionFilter("Poker","Poker"));
int value= chooser.showSaveDialog(this);
if(value== JFileChooser.APPROVE_OPTION)
{
File file= chooser.getSelectedFile();
System.out.println("Selected file " + file);
BufferedWriter writer= null;
try
{
writer= new BufferedWriter(new FileWriter(file));
writer.write(APP_ID);
writer.write(tax);
writer.write(money);
}
catch(Exception e)
{
System.out.println("Failed to write file: " + e);
}
finally
{
if(writer!= null)
{
try
{
writer.close();
}
catch(Exception e)
{
System.out.println("Failed to close file: " + e);
}
}
}
}
Let's say I have an URL, like something.domain/myfile.txt then I want to save this file, with that "Save File" dialog.
I tried my best to do it, but everytime I save the file using the dialog the file is not there.
An example or somewhere I can find information on this would help a lot!
URL website = null;
try {
website = new URL(<insert url here>);
} catch (MalformedURLException e) {
e.printStackTrace();
}
ReadableByteChannel rbc = null;
try {
rbc = Channels.newChannel(website.openStream());
} catch (IOException e2) {
e2.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("minecraft.jar"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (IOException e) {
e.printStackTrace();
}
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
File dir = fileChooser.getCurrentDirectory();
dir.mkdir();
//After this point is where I need help.
I trust that this is what you're looking for:
if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
// whatever you want to do with the file
System.out.println("The file is "+file.getAbsolutePath());
// fos = new FileOutputStream(file) ...
}
Did you notice that in your code you are trying to save/download the file before giving the user the option to chose the destination?
I would split the code into three different operations:
A method in charge of transferring the bytes from the InputStream (the web) to the OutputStream (the file).
a method to show the user a dialog so he can chose where to store the file.
the method that completes the whole task: choose a file and transfer the bytes from the web to it.
1) Would be something like this (you don't need to use the NIO API to implement it):
public void transfer(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[2048];
int bytesRead;
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
}
2) would be something very similar to what Dukeling has already stated:
public File chooseFile() {
File result = null;
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
result = fileChooser.getSelectedFile();
}
return result;
}
3) then, combining these two operations together is really simple:
public void saveFileFromWeb(URL url) {
File file = chooseFile(); // 1. Choose the destination file
if (file != null) {
// 2. Create parent folder structure
File folder = file.getParentFile();
if (!folder.exist()) {
folder.mkdirs();
}
InputStream in = null;
OutputStream out = null;
try {
// 3. Initialise streams
in = url.openStream();
out = new FileOuputStream(file);
// 4. Transfer data
transfer(in, out);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 5. close streams
if (in != null) {
try {
in.close();
} catch (IOException e) { /* ignore */ }
}
if (out != null) {
try {
out.close();
} catch (IOException e) { /* ignore */ }
}
}
}
NOTE: 1) and 2) could be private methods. Of course you could do this is just one single operation but splitting it would give you an overview of the different steps to perform.
NOTE 2: I simplified the exception handling part