How to save a file using FileChooser in JavaFX - javafx

How to save a file using FileChooser from JavaFX,
here's my sample:
public static void clickDownloadButton(String filename,Stage window){
File file = new File(filename);
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save file");
fileChooser.showSaveDialog(window);
}

Use java.nio.file.Files -
File dest = fileChooser.showSaveDialog(window);
if (dest != null) {
try {
Files.copy(file.toPath(), dest.toPath());
} catch (IOException ex) {
// handle exception...
}
}

Related

CLICK JAVAFXML BUTTON SCENEBUILDER

#FXML
void handleButtonAction(ActionEvent event) {
buttonOpenFile.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
openFiletxtField.setText(selectedFile.getAbsolutePath());
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}
}
});
buttonSaveFile.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File file = new File("Details.txt");
try {
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("whatever you need to write");
JOptionPane.showMessageDialog(null, "Saved Successfully..");
osw.flush();
osw.close();
} catch (IOException iOException) {
System.out.println("" + iOException.getMessage());
}
}
});
}
I Have a problem using javafx fxml button click event. Whenever I click the button once, nothing happens. I have to click it the second time for it to work? What could I be doing wrong? I have shared my code above. I am using scene builder I have everything in place apart from this error. everything is working fine apart from this issue. The code load text file from the computer directory and save the data to the loaded file.
#FXML
void handleOpenFileButtonAction(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
openFiletxtField.setText(selectedFile.getAbsolutePath());
}
}
#FXML
void handleSaveFileButtonAction(ActionEvent event) {
File file = new File("Details.txt");
try {
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(firstNametxtField.getText() + "," + lastNametxtField1.getText() + "," + enrolledCheckBox.isSelected() + "," + addresstxtField.getText() + "," + statesCombobox.getSelectionModel().getSelectedItem().toString() + "\n");
JOptionPane.showMessageDialog(null, "Saved Successfully..");
osw.flush();
osw.close();
} catch (IOException iOException) {
System.out.println("" + iOException.getMessage());
}
}

JavaFX FileChooser dir and file name passed to FileOutputStream

I have a download file button which once clicked will download a file from a website and save it to a location and name selected via FileChooser but I'm struggling to pass the file location and name to the FileOutputStream.
Does anybody have any suggestions please?
Thank you,
Paul
Here is my code:
public void GetFile()
{
try
{
URL url = new URL("https://www.myURL.com/MyFile.xlsx");
FileChooser saveAs = new FileChooser();
saveAs.setInitialFileName("MyFile.xlsx");
saveAs.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx"));
saveAs.showSaveDialog(null);
System.out.println("File name and location set");
saveFile(url,saveAs.getInitialDirectory());
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void saveFile(URL url, File saveAs) throws IOException {
System.out.println("opening connection");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(saveAs);
System.out.println("Reading file...");
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
System.out.println("File downloaded");
}
Use the return value of FileChooser.showSaveDialog instead of the initialDirectory property value:
File outputFile = saveAs.showSaveDialog(null);
if (outputFile != null) {
System.out.println("File name and location set");
saveFile(url, outputFile);
}

binding progress bar with a method, javafx

I have a method which performs some task(reading, writing files and other tasks also) for almost 3 minutes.
I want to bind progress bar in javafx which can run with progress of the method.
This is my method
System.out.println("Going to load contract/security:"+new Date());
Map<Integer,FeedRefData> map = loadContractAndSecurityFromFile(loadFO);
addIndicesRefData(map);
BufferedWriter writer = createFile();
for (FeedRefData feedRefData : map.values()) {
try {
updateInstrumentAlias(map, feedRefData);
String refDataString = feedRefData.toString();
writer.write(refDataString, 0, refDataString.length());
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
log.info("Unable to write Quote Object to : " );
}
}
System.out.println("Ref Data File Generated:"+new Date());
For bind your method with progressbar you should do these steps :
Create a task which contains your method.
Create a thread which run this task.
Bind your progress property with your task property.
I made this simple example ,just change my code with your method code :
public class Bind extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
ProgressBar pb = new ProgressBar();
pb.setProgress(1.0);
Button button = new Button("start");
button.setOnAction((ActionEvent event) -> {
/*Create a task which contain method code*/
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
File file = new File("C:\\Users\\Electron\\Desktop\\387303_254196324635587_907962025_n.jpg");
ByteArrayOutputStream bos = null;
try {
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
bos = new ByteArrayOutputStream();
for (int len; (len = fis.read(buffer)) != -1;) {
bos.write(buffer, 0, len);
updateProgress(len, file.length());
/* I sleeped operation because reading operation is quiqly*/
Thread.sleep(1000);
}
System.out.println("Reading is finished");
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
} catch (IOException e2) {
System.err.println(e2.getMessage());
}
return null;
}
};
Thread thread = new Thread(task);
thread.start();
/*bind the progress with task*/
pb.progressProperty()
.bind(task.progressProperty());
});
HBox box = new HBox(pb, button);
Stage stage = new Stage();
StackPane root = new StackPane();
root.getChildren().add(box);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}
Operation started :
Operation finished :
PS: I used Thread.sleep(1000) because my file is so small.You can remove it if your progress time is long.

Convert Bufferedimage to QPixmap Java QTJambi

I am using QTJambi and I need to convert BufferedImage into QPixmap.
I have found a solution:
public QPixmap convertBufferedImageToQPixmap(BufferedImage img){
QPixmap result = new QPixmap(new QSize(img.getWidth(),img.getHeight()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
boolean foundWriter = ImageIO.write(img, "jpg", baos);
result.loadFromData(baos.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

Upload file from applet to servlet using apache fileupload

To accomplish:
Upload a file from my local to server using an applet and servlet using apache fileupload jar.
Tried:
I have used a simple jsp, with a browse button and posted the action to my servlet (where I used apache fileupload). I was successful in uploading the file to the server.
Issue:
I am trying to upload a file, from my local machine, using an applet. I do not want to manually select files, instead upload files that are present in a specific folder. For now I have hardcoded the folder. I am able to look at the folder and get the list of files I want to upload.
Also, I have successfully established a connection from my applet to servlet.
Issue arises at the upload.parseRequest(request) in the servlet. I'm thinking its because the applet cannot post to servlet's request object.
Also, I have set the request type to multipart/form-data in my applet.
Right now, I am trying to pass the absolute path of the file to servlet and upload.
I have seen other posts where byte stream data is passed from applet to servlet, but the servlet uses the traditional File.write.
For me, it is mandatory to achieve this using apache fileupload.
Please suggest on how to pass a file/file path from applet to servlet, where the upload is handled by apache fileupload.
Below are my FileUploadHandler (where the HTTP requests are handled) and FileUpload(which is my applet)
Below is my FileUpload Handler:
#WebServlet(name = "FileUploadHandler", urlPatterns = { "/upload" })
#MultipartConfig
public class FileUploadHandler extends HttpServlet {
String uploadFolder ="";
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost-servlet URL is: "
+ request.getRequestURL());
try {
uploadFolder = fileToUpload(request);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
uploadFolder = getServletContext().getRealPath("")+ File.separator;
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// process only if its multipart content
if (ServletFileUpload.isMultipartContent(request)) {
System.out.println("Yes, it is a multipart request...");
try {
List<FileItem> multiparts = upload.parseRequest(request);
System.out.println("Upload.parseRequest success !");
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(uploadFolder + File.separator
+ name));
}
}
System.out.println("File uploaded to server !");
// File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to "
+ ex);
}
} if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
doGet(request, response);
//request.getRequestDispatcher("/result.jsp").forward(request, response);
OutputStream outputStream = response.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject("Success !");
objectOutputStream.flush();
objectOutputStream.close();
}
private String fileToUpload(HttpServletRequest request) throws IOException,
ClassNotFoundException {
ServletInputStream servletIn = request.getInputStream();
ObjectInputStream in = new ObjectInputStream(servletIn);
String uploadFile = (String) in.readObject();
System.out.println("Value in uploadFolder is: " + uploadFile);
return uploadFile;
}
Below is the fileupload applet:
public class FileUpload extends Applet {
private JButton capture;
private JTextField textField;
private final String pathDirectory = "C:\\";
private final String captureConfirmMessage = "Are you sure you want to continue?";
private final String confirmDialogTitle = "Confirm upload";
final File folder = new File(pathDirectory);
public void init() {
upload= new JButton("Upload");
textField = new JTextField();
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int selection = JOptionPane.showConfirmDialog(upload,
uploadConfirmMessage, confirmDialogTitle,
JOptionPane.YES_NO_OPTION);
if (selection == JOptionPane.OK_OPTION) {
listFilesForFolder(folder);
} else if (selection == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(upload,
"You have aborted upload", "Upload Cancelled", 2);
}
}
});
add(upload);
add(textField);
}
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
try {
onSendData(fileEntry.getAbsolutePath());
System.out.println(fileEntry.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Open the servlet connection
URL urlServlet = new URL("http://localhost:8081/UploadFile/upload");
HttpURLConnection servletConnection = (HttpURLConnection) urlServlet
.openConnection();
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestProperty("Content-Type", "multipart/form-data;");
servletConnection.connect();
return servletConnection;
}
private void onSendData(String fileEntry) {
try {
// Send data to the servlet
HttpURLConnection servletConnection = (HttpURLConnection) getServletConnection();
OutputStream outstream = servletConnection.getOutputStream();
ObjectOutputStream objectOutputStream= new ObjectOutputStream(
outstream);
objectOutputStream.writeObject(fileEntry);
// Receive result from servlet
InputStream inputStream = servletconnection.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(
inputStream);
String result = (String) objectInputStream.readObject();
objectInputStream.close();
inputStream.close();
out.flush();
out.close();
// Display result on the applet
textField.setText(result);
} catch (java.net.MalformedURLException mue) {
mue.printStackTrace();
textField.setText("Invalid serlvetUrl, error: " + mue.getMessage());
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
textField.setText("Couldn't open a URLConnection, error: "
+ ioe.getMessage());
} catch (Exception e) {
e.printStackTrace();
textField.setText("Exception caught, error: " + e.getMessage());
}
}
public void paint(Graphics g) {
g.drawString("Click the button above to capture", 5, 50);
}
I could finally succeed posting the request to the servlet from the applet.
It was a simple logic that I was missing. I did not add the header and trailer while posting to the servlet, which was the key, in the servlet to identify the incoming request as a multipart data.
FileInputStream fileInputStream = new FileInputStream(new File(
fileEntry));
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream
.writeBytes("Content-Disposition: form-data; name=\"upload\";"
+ " filename=\"" + fileEntry + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println(fileEntry + " uploaded.");
}
// send multipart form data necesssary after file data
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
I added the header and trailer and also used this to create the URL connection.
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Open the servlet connection
URL urlServlet = new URL("http://localhost:8083/UploadFile/upload");
HttpURLConnection servletConnection = (HttpURLConnection) urlServlet
.openConnection();
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestMethod("POST");
servletConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + this.boundary);
servletConnection.setRequestProperty("Connection", "Keep-Alive");
servletConnection.connect();
return servletConnection;
}
Then, in the servlet, I was just reading the data using upload.ParseRequest(request).
Thank you for the help.

Resources