Java - File save does not work - java

I would like to save an ArrayList's content to file (the user should choose the .txt's location) but I am not sure how to do that since that code does not work properly.
Do you have any idea how to do that?
package vizsgaquiz;
import java.io.File;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class VizsgaQuiz extends Application {
ArrayList<String> kerdeslista = new ArrayList<String>();
String a ="a";
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Foablak.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Quiz Játék");
stage.show();
save();
}
public void save(){
kerdeslista.add(a);
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(stage);
if(file != null){
SaveFile(kerdeslista, file);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

There are several issues that may be causing this problem. For starters, this code wouldn't compile. This is because you call the variable stage in the method save which "died" in the method start. To call stage in save, you either need to pass it to save or save it as a field. The second issue is that the method SaveFile doesn't seem to exist. An example of SaveFile might look something like the code included below. Please note that I updated the method save to take in a Stage and I changed the name of the method SaveFile to saveFile to match Java naming conventions. Also, the code below prints each value of the arraylist on a new line, which you may not want.
package vizsgaquiz;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class VizsgaQuiz extends Application {
ArrayList<String> kerdeslista = new ArrayList<String>();
String a ="a";
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Foablak.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Quiz Játék");
stage.show();
save(stage);
}
public void save(Stage stage){
kerdeslista.add(a);
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(stage);
if(file != null){
saveFile(kerdeslista, file);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public static void saveFile(ArrayList<String> list, File file) {
try {
PrintWriter out = new PrintWriter(file);
for (String val : list)
out.println(val + "\n");
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Here is an example how to save a new file to specified directory and name of file from FileDialog , Strings taken from a vector of Strings.It works for me !
public static void SaveFileTo(Vector<String> myLines) {
FileOutputStream f = null;
DataOutputStream h = null;
FileDialog d = new FileDialog(new JFrame(), "Save", FileDialog.SAVE);
d.setVisible(true);
String dir;
dir = d.getDirectory();
File oneFile = new File(dir + d.getFile());
try {
oneFile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
f = new FileOutputStream(oneFile);
h = new DataOutputStream(f);
for (String de : myLines) {
h.writeBytes(de);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
h.close();
f.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Related

Calling a function on the start of a JavaFX project using SceneBuilder

I created a GUI for my project using SceneBuilder and I set up all the button ID's and created a controller for the FXML file. I want to have a live clock running in the text area on launch and throughout the program. This is my first time using FXML to create a project in JavaFX so I'm confused as to where I should place this code. Normally the code works in a simple program without FXML and it is this code:
package com.example;
import example;
public class Layout extends Application {
TextArea clock;
public void start(Stage stage) throws FileNotFoundException {
clock = new TextArea();
clock.setEditable(false);
BorderPane bp = new BorderPane();
bp.setTop(clock);
refreshClock();
Scene scene = new Scene(bp);
stage.setScene(scene);
stage.show();
}
}
private void refreshClock()
{
Thread refreshClock = new Thread()
{
public void run()
{
while (true)
{
Date dte = new Date();
String topMenuStr = " " + dte.toString();
clock.setText(topMenuStr);
try
{
sleep(3000L);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} // end while ( true )
} // end run thread
};
refreshClock.start();
}
When I attempt to do it my current progress in my Ui controller class, nothing pops up in the Text Area despite what code I do and I'm not sure what to do next. Should this code be in my main .java file? Here is what I tried:
package application;
import java.util.Date;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
public class UiController {
#FXML
private TextArea clockTextArea;
private void refreshClock()
{
Thread refreshClock = new Thread()
{
public void run()
{
while (true)
{
Date dte = new Date();
String topMenuStr = " " + dte.toString();
clockTextArea.setText(topMenuStr);
try
{
sleep(3000L);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} // end while ( true )
} // end run thread
};
refreshClock.start();
}
public void initialize() {
refreshClock();
}
in javafx you work with events in the initialize() method.
E.g. button.setOnAction(e -> System.Exit(0)); or clock.onMouseClicked(e -> System.out.println("Test"));

Why is this program not playing my music files?

I was trying to create a basic music player in Java using JLayer library, but it doesn't seem to work. Nothing is played when I open a file (.mp3) through JFileChooser. Below is the code for my application. Please tell me what's wrong in it.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.swing.JFileChooser;
import javazoom.jl.player.Player;
import javazoom.jl.decoder.JavaLayerException;
class MusicPlayer
{
public void Player()
{
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try
{
File track = chooser.getSelectedFile();
FileInputStream trackstream = new FileInputStream(track);
BufferedInputStream bufferedtrack = new BufferedInputStream(trackstream);
try
{
Player player = new Player(bufferedtrack);
}
catch(JavaLayerException e)
{
System.out.println("Can't open file!");
}
}
catch(FileNotFoundException e)
{
}
}
else {
}
}
}
public class PlayerApp {
public static void main(String[] args) {
new MusicPlayer().Player();
}
}
You did miss out player.play() of the Player to start playing the requested file.
try
{
Player player = new Player(bufferedtrack);
player.play(); // add this line
}
catch(JavaLayerException e)
{
System.out.println("Can't open file!");
}
Also, method names are commonly written in camel-case (first letter lowercase). I recommend to rename your method void Player() to something like void loadDialogAndPlayFile().
You forgot to call the player.play(); method after Player player = new Player(bufferedtrack);

How can I continously check to see if the text inside a text file has changed to empty? Java

I have the following code in which I want to read what is in the text file and display in textField2 weather it has changed or not... If it has, then I need it to continue. If it hasn't, then I need it to check again until the file has been changed to empty. Can anyone help? Here is my code:
package application;
import javafx.event.ActionEvent;
import javafx.scene.control.TextField;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Parent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.FXML;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
// BorderPane root = new BorderPane();
Parent root = FXMLLoader.load(getClass().
getResource("Root.fxml"));
Scene scene = new Scene(root,550,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
#FXML
private TextField textField;
#FXML
private TextField textField2;
#FXML
protected void onClick(ActionEvent event) throws IOException {
BufferedWriter writer = null;
try {
//create a temporary file
// This will output the full path where the file will be written to...
writer = new BufferedWriter(new FileWriter("C:/Users/Custom/Documents/Sample.txt"));
writer.write(textField.getText());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
while (readFile("C:/Users/Custom/Documents/Sample.txt") != ""){
textField2.setText("Waiting...");
}
textField2.setText("Done!");
}
}
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}
you can check the time stamp of file to determine whether it has changed or not.
Sample code :
Long fileLastModified;
File file = new File("file");
if (!file.exists()) {
syserr
}
if (file.lastModified() <= this.fileLastModified) {
return oldValue;
}
this.fileLastModified = file.lastModified();
Also, you should use threads as commented by redflar3
Hi you can make a timer to check the file once every 2 seconds or so a snippet goes here
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
//Read your file
if(fileEmpty){
//Update your textfiled
cancel(); //Stops this timer
}
}
},
0,2000);
once your task is done just use purge(); to clear out all cancelled timers
hope this helps

JTextArea saving to txt

I'm making a program that requires to save user input. So I would like to know how to save JTextArea to text file and when you close and re-open program text is still in JTextArea.
Also sorry for my bad grammar.
package main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class main extends JFrame {
JLabel statusbar;
public main() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
statusbar = new JLabel("");
statusbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
panel.setLayout(null);
JTextArea area1;
area1 = new JTextArea(90, 25);
area1.setBounds(20, 20, 200, 25);
area1.setBackground(Color.white);
area1.setForeground(Color.BLACK);
area1.setText("");
panel.add(area1);
add(panel);
add(statusbar, BorderLayout.SOUTH);
setTitle("Viskis");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton o = (JButton) e.getSource();
String label = o.getText();
statusbar.setText("");
} }
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
main ms = new main();
ms.setVisible(true);
new main();
}
});
}
}
Here are some helper methods to help you read and write from Files. Look in the JavaDoc for getText() and setText() for getting and setting the text of the JTextArea.
I recommend reading the SwingWorker tutorials and using these methods in a SwingWorker, lest you lock up your GUI while saving/reading the Files
/**
* Writes a String text to a File specified by filename
*
* #param filename The filename/path of the File we would like to write the text to
* #param text The text to write to the File
*
*/
public static void writeToFile(String filename, String text) {
BufferedWriter writer = null; // This could go in a try-with-resources if you wanna get fancy
try {
writer = new BufferedWriter(new FileWriter(new File(filename))); // Open a File for writing
writer.write(text); // write the text to the file
} catch ( IOException e) {
/* We could not open the File for writing, or could not write to the File */
} finally {
try {
if (writer != null) {
writer.close(); // we are done writing to the File, close the connection
}
} catch (IOException e) {
/* We could not close the connection to the File */
}
}
}
/**
* Reads all lines from a File specified by filename
*
* #param filename The filename/path of the File we would like to read text from
*
* #return An list of Strings containing each line of the File
*/
public static List<String> readFromFile(String filename) {
BufferedReader reader = null; // This could go in a try-with-resources if you wanna get fancy
List<String> lines = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(new File(filename))); // Open a File for writing
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
/* We could not open the File for reading, or could not read from the File */
} finally {
try {
if (reader != null) {
reader.close(); // we are done reading from the File, close the connection
}
} catch (IOException e) {
/* We could not close the connection to the File */
}
}
return lines;
}
Write and read file on a swing thread is not recommanded. Use mvc pattern. Create a data model with field binded to your component. Create an adapter to update model and write file
Then your component will always up to date with your model
Use model to write data(with the adapter) and read file will update your model with the adapter
For exemple, Focus listener will call adapter to do the task. Or you can use an obseevee pattern when you Object if modified.
This code worked for me with 'nam' as the current date and 'name' an input in a jTextField.
try {
con=Connect.ConnectDB();
pst.execute();
Date date=new Date();
SimpleDateFormat sd=new SimpleDateFormat("dd-mm-yyyy-h-m-s");
String nam= sd.format(date);
String name=CaseNoField.getText();
CaseNoField.setText("");
FileWriter writer=new FileWriter( "C:\\path"+name+"("+nam+")"+".txt");
BufferedWriter bw=new BufferedWriter( writer );
JCaseArea.write( bw );
bw.close();
JCaseArea.setText("");
JCaseArea.requestFocus();
JOptionPane.showMessageDialog(null, "Case Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

Opening edrawingsviewer files from java

I have an application that I run on a pc with a mouse, I want to launch edrawingsviewer with a particular file name from java and then when the user returns to the fullscreen app, if they haven't closed it I want to close it. This is what I've got so far for a quick demo but I cannot figure out what to put in the arguments in order to launch solidworks with a particular file.
package com.protocase.hmiclient.edrawings;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* #author DavidH
*/
public class EDrawingHelper {
public static File[] getEDrawingsForJob(final String jobNumber) {
File f = new File("\\\\itsugar\\www\\HMI\\POD EDRAWINGS");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(jobNumber) && (name.endsWith("EASM") || name.endsWith("EDRW"));
}
});
return matchingFiles;
}
public static void test(String[] args) {
File[] files = getEDrawingsForJob("G080111004-13162-1");
for (File file : files){
System.out.println(file.getName());
}
}
public static void openEDrawingForFileName(String fileName){
try {
final Process process = Runtime.getRuntime().exec("C:\\Program Files\\SolidWorks Corp\\SolidWorks eDrawings (2)\\EModelViewer.exe \\\\itsugar\\www\\HMI\\POD EDRAWINGS\\"+fileName);
JFrame frame = new JFrame();
JButton killButton = new JButton("KILL");
killButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
process.destroy();
System.exit(0);
}
});
frame.getContentPane().add(killButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
openEDrawingForFileName("G080111004-13162-1 ASSEMBLY.EASM");
}
}
I don't think this is a solidworks problem, I think this is just something I'm passing wrong or formatting wrong or something.
It appears as if running it through the FileProtocolHandler causes it to open fine.
final Process process = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler \\\\itsugar\\www\\HMI\\POD EDRAWINGS\\"+fileName);

Categories