As you see, I've been researching and tried to set a thread in main.java class. This is the main method:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
check ch = new check();
ch.start();
}
});
}
Main method calls a thread called ch , from check.java class.
This is the thread class:
public class check extends Thread {
public JTextArea estado = new JTextArea();
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();
public String catchUpdatedVersion;
int UPDATENUMBER;
int CURRENTNUMBER;
public void run() {
String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
String name = "thread.inf";
File file = new File(name);
try {
URLConnection conn = new URL(infURL).openConnection();
conn.connect();
estado.append("Conectando al servidor...");
estado.append(System.getProperty("line.separator"));
estado.append(" -- Buscando actualizaciones... --");
estado.append(System.getProperty("line.separator"));
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(file);
int b = 0;
while (b != -1) {
b = in.read();
if (b != -1) {
out.write(b);
}
}
out.close();
in.close();
} catch (MalformedURLException ex) {
} catch (IOException ioe) { }
String fileToReadUpdatedVersion = "thread.inf";
try {
BufferedReader br = new BufferedReader(
new FileReader(fileToReadUpdatedVersion));
String brr = br.readLine();
catchUpdatedVersion = brr.substring(34,42);
String catchUpdatedShortVersion = brr.substring(15,16);
UPDATENUMBER = Integer.parseInt(catchUpdatedShortVersion);
String fileToReadCurrentVer = "thread.inf";
BufferedReader brrw = new BufferedReader(
new FileReader(fileToReadCurrentVer));
String brrwREAD = brrw.readLine();
String catchCurrentShortVersion = brrwREAD.substring(15,16);
CURRENTNUMBER = Integer.parseInt(catchCurrentShortVersion);
if (CURRENTNUMBER >= UPDATENUMBER) {
estado.setText("No se han encontrado actualizaciones.");
} else {
updatedVersion.setForeground(new Color(0,102,0));
updatedLabel.setForeground(new Color(0,153,51));
updatedVersion.setText(catchUpdatedVersion);
estado.append("-------------------" +
"NUEVA ACTUALIZACIÓN DISPONIBLE: " +
catchUpdatedVersion + " -------------------");;
estado.append(System.getProperty("line.separator"));
estado.append("Descargando actualizaciones... " +
"Espere por favor, no cierre este " +
"programa hasta que esté completado...");
try {
String updateURL = "https://thread.googlecode.com/" +
"svn/trunk/thread.inf";
String updatedname = (catchUpdatedVersion + ".zip");
File updatedfile = new File(updatedname);
URLConnection conn = new URL(updateURL).openConnection();
conn.connect();
estado.append(System.getProperty("line.separator"));
estado.append(" Archivo actual: " + updatedname);
estado.append(System.getProperty("line.separator"));
estado.append(" Tamaño: " +
conn.getContentLength() / 1000 / 1000 + " MB");
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(updatedfile);
int c = 0;
while (c != -1) {
c = in.read();
if (c != -1) {
out.write(c);
}
}
out.close();
in.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
} catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}
}
}
When I run the program, the thread does not work fine. It is supposed to download a file and then display its progress in a JTextArea in main.java class. It does download the file, but nothing appears in JTextArea.
Where is my mistake?
EDIT: Showing all the code.
Problem #1
The components you are trying to update are not, in any way, connected to the screen...
public JTextArea estado = new JTextArea();
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();
That means, anytime you interact with these components, it's doing nothing to what's on the screen...
Problem #2
You're trying to make modifications to the UI from outside the context of the Event Dispatching Thread. This is significant violation of the Swing threading rules.
public class Check extends SwingWorker<String, String> {
private JTextArea estado;
Private JTextField updatedVersion;
private JLabel updatedLabel;
private String catchUpdatedVersion;
int UPDATENUMBER;
int CURRENTNUMBER;
public Check(JTextArea estado, JTextField updatedVersion, JLabel updatedLabel) {
this.estado = estado;
this.updatedVersion = updatedVersion;
this.updatedLabel = updatedLabel;
}
protected void process(List<String> values) {
for (String value : values) {
estado.append(value);
}
}
protected String doInBackground() throws Exception {
String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
String name = "thread.inf";
File file = new File(name);
URLConnection conn = new URL(infURL).openConnection();
conn.connect();
publish("Conectando al servidor...");
publish(System.getProperty("line.separator"));
publish(" -- Buscando actualizaciones... --");
publish(System.getProperty("line.separator"));
/*...*/
}
}
IfYou need to do any post-processing, then you also override done which will be called after doInBackground has existed, but is called within the context of the EDT
For more details read through Concurrency in Swing
Related
So I'm doing this app for a coursework project and I am getting this error when I try to communicate with server:
java.io.StreamCorruptedException: invalid stream header: 43686F6F
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at Client.ChatClient.<init>(ChatClient.java:31)
at Client.ChatClient.main(ChatClient.java:102)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Here is my Server Code:
public class ChatServer implements Observer {
private ServerSocket serverSocket = null;
private ArrayList<ClientHandler> clients = null;
private Executor service = Executors.newFixedThreadPool(10);
public ChatServer( int port ) {
try {
serverSocket = new ServerSocket( port );
}
catch (IOException e) {
e.printStackTrace();
}
clients = new ArrayList<ClientHandler>();
Thread t = new Thread( new ServerLoop() );
t.start();
}
public void tellEveryone( String message ) {
Iterator it = clients.iterator();
while ( it.hasNext() ) {
System.out.println( 1 );
ClientHandler client = (ClientHandler) it.next();
client.send(message);
}
System.out.println( message );
}
#Override
public void update(Observable o, Object arg) {
System.out.println("from server - updateMethod : " + arg );
}
public class ServerLoop implements Runnable {
public void run() {
try {
while (true) {
Socket clientSocket = serverSocket.accept();
ClientHandler c = new ClientHandler(clientSocket);
clients.add(c);
c.addObserver(ChatServer.this);
service.execute(c);
tellEveryone("new client");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main( String[] args ) {
ChatServer s = new ChatServer( 5000 );
}
}
This is my Client Handler (main part):
public class ClientHandler extends Observable implements Runnable {
private Scanner reader = null;
private PrintWriter writer = null;
private String path = "../";
private Socket client;
private BufferedOutputStream bufferedOutputStream;
private boolean isConnected = false;
private ObjectOutputStream outputStream = null;
private String sourceDirectory = "/home/csunix/sc16hsm/IdeaProjects/ServerClient/src/Server/folder1";
private String destinationDirectory = "/home/csunix/sc16hsm/IdeaProjects/ServerClient/src/Client/Downloads/";
private int fileCount = 0;
private FileEvent fileEvent = null;
public ClientHandler( Socket client ) {
try {
this.client=client;
reader = new Scanner( client.getInputStream() );
writer = new PrintWriter( client.getOutputStream(), true );
bufferedOutputStream = new BufferedOutputStream(client.getOutputStream());
}
catch (IOException e) {
e.printStackTrace();
}
}
public void locateFiles() {
File srcDir = new File(sourceDirectory);
if (!srcDir.isDirectory()) {
System.out.println("Source directory is not valid ..Exiting the client");
System.exit(0);
}
File[] files = srcDir.listFiles();
fileCount = files.length;
if (fileCount == 0) {
System.out.println("Empty directory ..Exiting the client");
System.exit(0);
}
for (int i = 0; i < fileCount; i++) {
System.out.println("Sending " + files[i].getAbsolutePath());
sendFile(files[i].getAbsolutePath(), fileCount - i - 1);
System.out.println(files[i].getAbsolutePath());
}
}
public void sendFile(String fileName, int index) {
fileEvent = new FileEvent();
fileEvent.setDestinationDirectory(destinationDirectory);
fileEvent.setSourceDirectory(sourceDirectory);
File file = new File(fileName);
fileEvent.setFilename(file.getName());
fileEvent.setRemainder(index);
DataInputStream diStream = null;
try {
diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0; int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read, fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
try {
outputStream.writeObject(fileEvent);
} catch (IOException e) {
e.printStackTrace();
}
}
public void listFolders(){
File file = new File("../");
String[] directories = file.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
send(Arrays.toString(directories));
}
public void listAll(String fileName){
File folder = new File(path + "/" + fileName);
path = folder.getPath();
System.out.println(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
writer.println("File: " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
writer.println("Directory: " + listOfFiles[i].getName());
}
}
}
public void send( String message ) {
writer.println( message );
}
public void run() {
String message;
writer.println("Choose a file");
listAll("");
while ((message = reader.nextLine()) != null) {
writer.println("Choose a file");
listAll(message);
setChanged();
notifyObservers( message );
if(message.equals("download")) {
System.out.println("MESSAGE FROM CLIENT: " + message);
writer.println("ready");
locateFiles();
}
}
}
}
This is my Client code:
public class ChatClient {
private Scanner socketIn = null;
private PrintWriter socketOut = null;
private Scanner keyboardIn = null;
private Socket socket = null;
private ObjectInputStream inputStream = null;
private FileEvent fileEvent;
private File dstFile = null;
private FileOutputStream fileOutputStream = null;
public ChatClient( String host, int port ) {
try {
Socket socket = new Socket( host, port );
socketIn = new Scanner( socket.getInputStream() );
socketOut = new PrintWriter( socket.getOutputStream(), true );
keyboardIn = new Scanner( System.in );
inputStream = new ObjectInputStream(socket.getInputStream());
}
catch( IOException e ) {
e.printStackTrace();
}
}
public void downloadFiles() {
while (socket.isConnected()) {
try {
fileEvent = (FileEvent) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Error occurred ..with file" + fileEvent.getFilename() + "at sending end ..");
}
String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
if (!new File(fileEvent.getDestinationDirectory()).exists()) {
new File(fileEvent.getDestinationDirectory()).mkdirs();
}
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");
if (fileEvent.getRemainder() == 0) {
System.out.println("Whole directory is copied...So system is going to exit");
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
private void talktoServer() {
String message;
Thread readerThread = new Thread( new IncomingReader() );
readerThread.start();
while ((message = keyboardIn.nextLine()) != null) {
System.out.println("client typed: " + message);
socketOut.println( message );
}
}
private class IncomingReader implements Runnable {
public void run() {
String message;
while ((message = socketIn.nextLine()) != null) {
System.out.println("client read: " + message);
if(message.equals("ready")) {
downloadFiles();
}
}
}
}
public static void main( String[] args ) {
ChatClient c = new ChatClient( "127.0.0.1", 5000 );
c.talktoServer();
}
}
Any help at all would be greatly appreciated!
I created a class Students, that invokes a thread which needs to fill a linked list with students.
class Students{
private LinkedList<Student> students = new LinkedList<Student>();
android.os.Handler handler = new android.os.Handler();
public String Fill() throws MalformedURLException {
String msg = "++";
new Thread(){
public void run(){
HttpURLConnection htcon=null;
try {
URL my_url = new URL("http://www.whatever.net/fill.php");
htcon = (HttpURLConnection) my_url.openConnection();
htcon.setDoOutput(true);
htcon.setUseCaches(false);
htcon.connect();
int responseCode = htcon.getResponseCode();
if(responseCode ==HttpURLConnection.HTTP_OK){
InputStream stream = htcon.getInputStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
String line = "";
StringBuilder strbld = new StringBuilder();
while ((line = bfr.readLine()) != null) {
strbld.append(line);
}
if (bfr!=null)
{
bfr.close();
}
String[] ary = strbld.toString().split("\n");
for (int i = 0; i < ary.length; i++) {
final Student temp = new Student(ary[i].toString().split(":")[0], "1210",Integer.parseInt(ary[i].toString().split(":")[1]), 0);
handler.post(new Runnable() {
#Override
public void run() {
students.push(new Student("jjj","k",9,9));
}
});
}//for
if (htcon!=null)
htcon.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
}.start();
return toBinaryString(students.size());
}
problem is, when handler runs, it doesn't change the list. size is still 0
here is how my UI class looks like(main activity)
TextView txtv = (TextView) findViewById(R.id.textv);
Students students1 = new Students();
try {
msg = students1.Fill();
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
}
Your thread is running asynchronously. So, it will immediately execute:
return toBinaryString(students.size());
while the thread is still on the progress. AsyncTask is really enough for your problem. Hope it helps.
I've created an app with utilities I usually use on my pc (like sending shutdown to cmd.exe) and as some friends asked me to give it to them I was trying to add an update system that checks for updates on a server to make it easier that their version is always updated.
The thing is that I've been over the net searching any solution but all of them just tell to use .close() and my file has it right after stop needing it. When I run it everything works fine and there are no exceptions thrown, so I just dunno what can be wrong.
Whole class:
public class Main_Gui extends JFrame {
private Thread worker;
private final String root = "update/";
private JTextArea outText;
private JButton cancel;
private JButton launch;
private JScrollPane sp;
private JPanel pan1;
private JPanel pan2;
private String zipFile = "Actualización.zip";
private String path = "http://ritsu.hol.es/url.html";
private String TITLE = "RitsUtilities | Actualizador";
public Main_Gui() {
initComponents();
outText.setText("Conectando con el servidor...");
download();
}
private void initComponents() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle(TITLE);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pan1 = new JPanel();
pan1.setLayout(new BorderLayout());
pan2 = new JPanel();
pan2.setLayout(new FlowLayout());
outText = new JTextArea();
sp = new JScrollPane();
sp.setViewportView(outText);
launch = new JButton("Ejecutar RitsUtilities");
launch.setEnabled(false);
launch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] run = { "java", "-jar", "RitsUtilities.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
launch();
}
});
pan2.add(launch);
cancel = new JButton("Salir");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pan2.add(cancel);
pan1.add(sp, BorderLayout.CENTER);
pan1.add(pan2, BorderLayout.SOUTH);
add(pan1);
pack();
setSize(500, 400);
setLocationRelativeTo(null);
}
private void download() {
worker = new Thread(new Runnable() {
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
});
worker.start();
}
private void launch() {
String[] run = { "java", "-jar", "update app.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}
private void cleanup() {
outText.setText(outText.getText() + "\nLimpiando archivos temporales...");
remove(new File(root));
new File(root).delete();
}
private void remove(File f) {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
remove(ff);
ff.delete();
} else {
ff.delete();
}
}
}
private void copyFiles(File f, String dir) throws IOException {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
new File(dir + "/" + ff.getName()).mkdir();
copyFiles(ff, dir + "/" + ff.getName());
} else {
copy(ff.getAbsolutePath(), dir + "/" + ff.getName());
}
}
}
public void copy(String srFile, String dtFile) throws FileNotFoundException, IOException {
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();
}
private void unzip() throws IOException {
int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(zipFile);
Enumeration e = zipfile.entries();
(new File(root)).mkdir();
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
outText.setText(outText.getText() + "\nExtrayendo: " + entry);
if (entry.isDirectory())
(new File(root + entry.getName())).mkdir();
else {
(new File(root + entry.getName())).createNewFile();
is = new BufferedInputStream(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(root + entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
}
private void downloadFile(String link) throws MalformedURLException, IOException {
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long max = conn.getContentLength();
outText.setText(outText.getText() + "\n" + "Descargando archivo...\nTamaño de la actualización(comprimida): " + max + " Bytes");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile)));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
int in = 0;
while ((bytesRead = is.read(buffer)) != -1) {
in += bytesRead;
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
outText.setText(outText.getText() + "\n¡Descarga completada!");
}
private String getDownloadLinkFromHost() throws MalformedURLException, IOException {
URL url = new URL(path);
InputStream html = null;
html = url.openStream();
int c = 0;
StringBuilder buffer = new StringBuilder("");
while (c != -1) {
c = html.read();
buffer.append((char) c);
}
return buffer.substring(buffer.indexOf("[url]") + 5, buffer.indexOf("[/url]"));
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main_Gui().setVisible(true);
}
});
}
}
EDIT: changed private String zipFile = "Actualización.zip"; to private String zipFile = "Update.zip"; but still just deleting temp files/directories but not that "Update.zip" folder that the app downloads.
The File#delete() method you are using doesn't throw an error if the file can't be deleted, it returns false. This is documented in the Javadoc, together with an alternative solution (emphasize mine):
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
Finally it's working, just added a forced delete on run() inside download() so now my code looks like
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
+ System.gc();
+ File tmpf = new File(zipFile);
+ tmpf.deleteOnExit();
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
I'm pretty sure that there are way better ways to do this, but that one seems to work for me.
Thanks to everyone that answered and tried to help me. =D
I would suggest improving your remove(File f) method. Add some checks for the Boolean return value of ff.delete(), that will tell you if the file is actually being deleted or not.
Also, you could add some logs into that method, so you could debug what is actually doing, perhaps it's not seeing the files or something.
One last comment. You should make your code more modular. Create more abstractions and give each of them a simple task. That is the essence of Object Oriented Design. Then, you can program some JUnit tests for each object, and you can run the tests every time you make a change. I reccomend you give a look to this article on Cohesion
I have this app that runs in eclipse's console and I want it to run in a jframe.
By that I mean that I want it to ask for name, a and b on the JFrame window and then write something on a file.
It works perfectly in the console but I don't know how to run it as a JFrame.
I want it to look something like this(Image made in photoshop):
http://i.imgur.com/rTWko1R.png
And then automaticaly close
Thanks in advance!
some imports...(trying to save space)
public class Test {
public static void main(String[] args) throws FileNotFoundException,IOException {
Scanner s = new Scanner(System.in);
String fileName = new SimpleDateFormat("dd-MM-yyyy_HH-mm'.txt'").format(new Date());
String obs;
String name;
String path = "some path";
int a = 0, b = 0, c = 0, d = 0;
System.out.println("input file name");
name = s.nextLine();
System.out.println("input a");
a = s.nextInt();
System.out.println("input b");
b = s.nextInt();
obs = s.nextLine();
if (a >= 100) {
d = a / 100;
c = a % 100;
b = c;
a = a + d;
}
File file;
if (StringUtils.isBlank(name)) {
file = new File(path + fileName);
} else {
file = new File(path + name + "#" + fileName);
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("something");
if (StringUtils.isBlank(obs)) {
writer.write("something");
} else {
writer.write(obs + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
What you'll need to do
separate out your core logic into a separate method that takes String name, int a, int b, ideally in a separate class - then you can reuse from your console version
Create a basic GUI in a frame with a button to kick off the process
listen to the button press and call core logic method
add validation of inputs if necessary
consider using JFileChooser to allow user to pick the file rather than having to type it in
Example
public class ConsoleInFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ConsoleInFrame().showGui();
}
});
}
public void showGui() {
JFrame frame = new JFrame();
JTextField file = new JTextField(20);
JTextField aText = new JTextField(4);
JTextField bText = new JTextField(4);
JButton go = new JButton("Go");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("File"));
panel.add(file);
panel.add(new JLabel("a"));
panel.add(aText);
panel.add(new JLabel("b"));
panel.add(bText);
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.getContentPane().add(panel);
frame.getContentPane().add(go);
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
process(file.getText(), Integer.parseInt(aText.getText()),
Integer.parseInt(bText.getText()));
}
});
frame.pack();
frame.setVisible(true);
}
public void process(String name, int a, int b) {
String fileName = new SimpleDateFormat("dd-MM-yyyy_HH-mm'.txt'")
.format(new Date());
String obs;
String path = "some path";
int c = 0, d = 0;
if (a >= 100) {
d = a / 100;
c = a % 100;
b = c;
a = a + d;
}
File file;
if (StringUtils.isBlank(name)) {
file = new File(path + fileName);
} else {
file = new File(path + name + "#" + fileName);
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("something");
if (StringUtils.isBlank(obs)) {
writer.write("something");
} else {
writer.write(obs + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
I think you could do something like this:
To do this you have to use JLabel to display text: https://docs.oracle.com/javase/tutorial/uiswing/components/label.html
Then to get the input use JTextField:
https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
And if you want you can use a JButton after you write in the JTextField to save everything to the file:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
http://www.javamex.com/tutorials/swing/jbutton.shtml
I'm trying to save a mp3 file from the server to the client and play it after that. I am loading the playlist and after that trying to play a song(The song is supposed to be saved on the client PC and played after that). I am building the application with JavaFXpackage main;
Controller class:
public class AudioController {
#FXML
private ResourceBundle resources;
#FXML
private URL location;
#FXML
private Button nextButton;
#FXML
private Button playButton;
#FXML
private ListView<String> playlist;
#FXML
private Button previousButton;
#FXML
private Button stopButton;
#FXML
void initialize() {
final AudioClient audioClient = new AudioClient("127.0.0.1", 3000);
audioClient.setUpConnection();
ArrayList<String> songList = audioClient.getPlaylist();
ObservableList<String> songs = FXCollections
.observableArrayList(songList);
playlist.setItems(songs);
playButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
String songToPlay = playlist.getSelectionModel()
.getSelectedItem();
if (songToPlay != null) {
try {
String linkToSong = audioClient.getSong(songToPlay);
Media song = new Media(linkToSong);
MediaPlayer mediaPlayer = new MediaPlayer(song);
mediaPlayer.play();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
}
Client class
public class AudioClient {
protected BufferedReader socketReader;
protected PrintWriter socketWriter;
protected InputStream is;
protected String hostIP;
protected int hostPort;
public AudioClient(String hostIP, int hostPort) {
this.hostIP = hostIP;
this.hostPort = hostPort;
}
public ArrayList<String> getPlaylist() {
ArrayList<String> fileLines = new ArrayList<String>();
try {
socketWriter.println("Playlist");
socketWriter.flush();
String line = null;
while ((line = socketReader.readLine()) != null) {
fileLines.add(line);
}
} catch (IOException e) {
System.out.println("There was a problem reading");
}
return fileLines;
}
public String getSong(String songName) throws IOException {
socketWriter.println("Request " + songName);
socketWriter.flush();
String filePath = new String("D:\\" + songName + ".mp3");
FileOutputStream fos = new FileOutputStream(new File(filePath));
BufferedOutputStream bos = new BufferedOutputStream(fos);
int count;
byte[] buffer = new byte[4096];
while ((count = is.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, count);
}
return filePath;
}
public void setUpConnection() {
try {
Socket client = new Socket(hostIP, hostPort);
socketReader = new BufferedReader(new InputStreamReader(
client.getInputStream()));
InputStream is = client.getInputStream();
socketWriter = new PrintWriter(client.getOutputStream());
} catch (UnknownHostException e) {
System.out.println("Error setting up socket connection: unknown host at "
+ hostIP + ":" + hostPort);
} catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
}
}
public void tearDownConnection() {
try {
socketWriter.close();
socketReader.close();
} catch (IOException e) {
System.out.println("Error tearing down socket connection: " + e);
}
}
Class for handling connections to the server
public class ConnectionHandler implements Runnable {
private Socket socketToHandle;
public ConnectionHandler(Socket aSocketToHandle) {
socketToHandle = aSocketToHandle;
}
#Override
public void run() {
try {
PrintWriter streamWriter = new PrintWriter(
socketToHandle.getOutputStream());
BufferedReader streamReader = new BufferedReader(
new InputStreamReader(socketToHandle.getInputStream()));
String songToPlay = null;
while ((songToPlay = streamReader.readLine()) != null) {
if (songToPlay.equals("Playlist")) {
File songsTxt = new File(
"D:/Universitet i dr/JAVA/AudioPlayer/src/main/media/songsList.txt");
String song = null;
try {
FileReader reader = new FileReader(songsTxt);
BufferedReader songReader = new BufferedReader(reader);
while ((song = songReader.readLine()) != null) {
streamWriter.println(song);
}
} catch (FileNotFoundException e) {
System.out.println("File dosen't exist");
} catch (IOException e) {
System.out.println("Can't read from the file");
}
} else if (songToPlay.startsWith("Request ")) {
songToPlay = songToPlay.replaceFirst("Request ", "");
File songPath = new File(
"D:/Universitet i dr/JAVA/AudioPlayer/src/main/media/"
+ songToPlay);
BufferedInputStream inStream = new BufferedInputStream(
new FileInputStream(songPath));
BufferedOutputStream outStream = new BufferedOutputStream(
socketToHandle.getOutputStream());
byte[] buffer = new byte[4096];
for (int read = inStream.read(buffer); read >= 0; read = inStream.read(buffer)) {
outStream.write(buffer, 0, read);
}
}
}
} catch (Exception e) {
System.out.println("Error handling a client: " + e);
}
}