Strange behaviour when writing/reading from a txt file in Java - java

I am writing a GUI for a minesweeper and I am saving the difficulty in a text file. However instead of writing to file the difficulty properly, it always empties the file and my null check condition is triggered.
I have tried using debugging and manually editing the text file to contain the string "HARD", but after changing the difficulty (setting it again to hard, or switching to easy), the file becomes empty.
public class MineSweeperMain extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
String difficulty;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("LastProgramState.txt"));
difficulty = br.readLine();
if (difficulty == null) {
System.out.println("???");
throw new FileNotFoundException(); // If I comment this out, file becomes empty
}
} catch (FileNotFoundException e) {
BufferedWriter bw = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bw.write("EASY");
bw.close();
difficulty = "EASY";
} finally {
if (br != null)
br.close();
}
int xSize;
int ySize;
int bombCount;
System.out.println(difficulty);
if (difficulty == null) {
System.exit(200);
}
if (difficulty.equals("HARD")) {
xSize = 16;
ySize = 16;
bombCount = 40;
}
else {
xSize = 9;
ySize = 9;
bombCount = 10;
}
Menu menu1 = new Menu("Options");
Menu menu2 = new Menu("Help");
MenuItem mi1 = new MenuItem("Difficulty: Easy");
MenuItem mi2 = new MenuItem("Difficulty: Hard");
MenuItem mi3 = new MenuItem("How to play");
MenuItem mi4 = new MenuItem("About...");
menu1.getItems().add(mi1);
menu1.getItems().add(mi2);
menu2.getItems().add(mi3);
menu2.getItems().add(mi4);
MenuBar bar = new MenuBar();
bar.getMenus().addAll(menu1,menu2);
Label score = new Label("Score:");
Scene scene = new Scene(bp);
primaryStage.setScene(scene);
primaryStage.setTitle("MineSweeper");
primaryStage.show();
}
mi1.setOnAction(event -> { //EASY
try {
BufferedWriter bwriter = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bwriter.write("EASY");
} catch (IOException e) {
System.exit(100);
}
primaryStage.close();
Platform.runLater( () -> { //RUN APPLICATION AGAIN
try {
new MineSweeperMain().start( new Stage() );
} catch (Exception ex) {
System.exit(100);
}
} );
});
mi2.setOnAction(event -> { //HARD
try {
BufferedWriter bwriter = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bwriter.write("HARD");
} catch (IOException e) {
System.exit(100);
}
primaryStage.close();
Platform.runLater( () -> {
try {
new MineSweeperMain().start( new Stage() );
} catch (Exception ex) {
System.exit(100);
}
} );
});
}
If I choose hard difficulty, I expect the txt file to contain the string "HARD", but instead it contains the string "EASY". The same behaviour occurs when I choose easy difficulty. Also I noticed that if I remove the throw new FileNotFoundException(), the file becomes completely empty. What am I doing wrong? Any help is appreciated.
EDIT: Issue solved, I forgot to close the file after writing to in in mi1.setOnAction() and mi2.setOnAction().

Related

It seems like my module is not loading and saving String arrays properly. Why?

I'm having a problem with my methods for a school assignment which are supposed to load and save String arrays to a file. It seems like it does not save or load properly. For example, I saved a string of "ok" in a file, let's call it x. Then I rerun the app and changed the path to a directory and it read the string "ok" from it even though it wasn't initially saved the directory and the directory shouldn't be allowed anyways. I really don't know how to solve it and I tried to manipulate the code but I do not know what causes it so it's hard to think of a solution.
Some details on my task:
have to use File Output/Input Stream and Object Output/Input Stream
question and answer strings have to be initialized to 0 size if the path is empty/is a dir/ file not found
take answer and question string from textfield, save it to a file and read the existing ones from the file
question and answer string arrays have to be in a separate class
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
public class App2 extends JFrame implements ActionListener {
JPanel mpanel, qpanel, apanel, bpanel, upanel;
JTextField tf1, tf2, tf3;
JButton jb;
JLabel jl1, jl2, jl3;
String path;
public static void main(String[] args) {
App2 object = new App2();
System.out.println("app init/ array size:" + QAData.question.length);
}
App2() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(400, 200);
this.setTitle("App2");
mpanel = new JPanel();
this.add(mpanel);
mpanel.setLayout(new GridLayout(4, 1));
qpanel = new JPanel();
mpanel.add(qpanel);
apanel = new JPanel();
mpanel.add(apanel);
upanel = new JPanel();
mpanel.add(upanel);
bpanel = new JPanel();
mpanel.add(bpanel);
jl1 = new JLabel("Question: ");
qpanel.add(jl1);
tf1 = new JTextField(20);
tf1.setHorizontalAlignment(JTextField.LEFT);
qpanel.add(tf1);
tf1.addActionListener(this);
jl2 = new JLabel("Answer: ");
apanel.add(jl2);
tf2 = new JTextField(20);
tf2.setHorizontalAlignment(JTextField.LEFT);
apanel.add(tf2);
tf2.addActionListener(this);
jl3 = new JLabel("Path: ");
upanel.add(jl3);
tf3 = new JTextField(20);
tf3.setHorizontalAlignment(JTextField.LEFT);
upanel.add(tf3);
tf3.addActionListener(this);
jb = new JButton("Update");
jb.setHorizontalAlignment(JButton.CENTER);
bpanel.add(jb);
jb.addActionListener(this);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == tf3)
path = tf3.getText();
if (e.getSource() == jb) {
load();
save();
tf1.setText("");
tf2.setText("");
}
}
void load() {
try {
File file = new File("path");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (!fileIsOk) {
QAData.question = new String[0];
QAData.answer = new String[0];
System.out.println("size 0 applied");
} else {
QAData.question = (String[]) ois.readObject();
QAData.answer = (String[]) ois.readObject();
}
ois.close();
} catch (ClassNotFoundException e) {
System.out.println("No such class found");
e.printStackTrace();
} catch (IOException e) {
System.out.println("I/O exception during the load");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to read has the null value");
e.printStackTrace();
}
}
void save() {
try {
File file = new File("path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (fileIsOk) {
QAData.question = Arrays.copyOf(QAData.question, QAData.question.length + 1);
QAData.question[(QAData.question.length - 1)] = tf1.getText();
QAData.answer = Arrays.copyOf(QAData.answer, QAData.answer.length + 1);
QAData.answer[(QAData.answer.length - 1)] = tf2.getText();
oos.writeObject(QAData.question);
oos.writeObject(QAData.answer);
}
oos.close();
} catch (IOException e) {
System.out.println("I/O exception during the save");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to save has the null value");
e.printStackTrace();
}
}
static class QAData implements Serializable {
static String[] question = new String[0];
static String[] answer = new String[0];
}
}

Java Swing : JTabbed for putting new component in tab

I am developing Swing Application . I create new Tab for new Log Process..Print all console statement inside it . when i place tab in tab component it get mismatched pro1 hold log2 pro2 hold log1 so i dig to much but not figure out code is follow.
ProjectExecute Event Which call to CreateNew TAb Method .
if (e.getSource() == btnExecute) {
createTab();
String s = new StringBuffer().append(ProjectOutPath).toString();
dirr = new File(s);
if (!dirr.exists()) {
}
final File tagFile = new File(dirr, projectName + ".log");
if (!tagFile.exists()) {
try {
tagFile.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
SwingWorker<Boolean, Integer> worker = new SwingWorker<Boolean, Integer>() {
#SuppressWarnings({ "unchecked", "null" })
#Override
protected Boolean doInBackground() throws Exception {
PrintStream printStream = new PrintStream(new CustomOutputStream(logTextArea, tempArea));
System.setOut(printStream);
System.setErr(printStream);
File outFile = new File(tagFile.getAbsolutePath());
FileOutputStream outFileStream = new FileOutputStream(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);
try {
System.out.println("ChooserFile 1 :" + chooserFile1);
MainApp.runApp(chooserFile1);
chooserFile1 = new StringBuilder().append(chooserFile1).append("/raw_data").toString();
outStream.write(logTextArea.getText());
System.out.flush();
Runtime.getRuntime().exec("clear");
outStream.close();
printStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Thread.sleep(1000);
return true;
}
protected void done() {
try {
Component c[] = panel_tree.getComponents();
panel_tree.remove(c.length - 1);
panel_tree.add(ExomDataGUI.getTreeUpdate());
panel_tree.revalidate();
panel_tree.repaint();
scrollPane.getViewport().setView(ExomDataGUI.panel_tree);
} catch (Exception e) {
System.out.println("Exception Occured....!");
}
}
#Override
protected void process(List<Integer> chunks) {
int mostRecentValue = chunks.get(chunks.size() - 1);
countLabel.setText(Integer.toString(mostRecentValue));
}
};
worker.execute();
} else {
}
}
Create TAB method
private static JScrollPane createScroll() {
System.out.println("Creatre Scrollpane Method Called....");
JTextArea ja = new JTextArea();
String S = logTextArea.getText();
ja.setText(S);
JScrollPane JScrolling = new JScrollPane(ja);
logTextArea.setText(null);
return JScrolling;
}
public static void createTab() {
JLabel lblTitle;
if (flag == 1) {
//System.out.println("************Inside If Flag ***********");
tabbedPane1.add("", new JScrollPane(logTextArea));
Demo.add(tabbedPane1);
JTextArea JTA = new JTextArea();
String log = logTextArea.getText();
JTA.setText(log);
logTextArea.setText(null);
lblTitle= new JLabel(projectName);
flag = 0;
} else {
// System.out.println("+++++++++++++++++++Inside If Flag +++++++++++");
JScrollPane JSP = createScroll();
tabbedPane1.add("here", JSP);
lblTitle= new JLabel(projectName);
}
JPanel pnlTab = new JPanel();
pnlTab.setOpaque(false);
//JLabel lblTitle = new JLabel();
JButton btnClose = new JButton();
btnClose.setOpaque(false);
btnClose.setRolloverIcon(CLOSE_TAB_ICON);
btnClose.setRolloverEnabled(true);
btnClose.setIcon(CLOSE_TAB_ICON);
btnClose.setBorder(null);
btnClose.setFocusable(false);
pnlTab.setForeground(Color.white);
pnlTab.setBackground(Color.white);
pnlTab.add(lblTitle);
pnlTab.add(btnClose);
pnlTab.setForeground(Color.white);
tabbedPane1.setTabComponentAt(tabbedPane1.getTabCount() - 1, pnlTab);
Demo.add(tabbedPane1);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int response = JOptionPane.showConfirmDialog(null, "Do You Want To Close Tab ?");
if (response == 0)
tabbedPane1.remove(tabbedPane1.getSelectedComponent());
tabIndex--;
}
};
btnClose.addActionListener(listener);
}

.zip file isn't deleted but neither throw any exception

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

JFrame Console Scanner

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

indexoutofboundsexception by sending pictures over Socket

I want to make a little programm that makes a live-stream for Desktop.
It should be so that you send pictures to an echo-server and he response it to the clients.
There you get be draw the Images. Side by Side. And so it is like a movie(or something like that).
But I always get an indexoutofboundsexception. Where is the error or how can I improve my program.
The ImageIO.write lines thows the Error
//Client Main
public class Main {
public static void main(String[] args) {
Frame frm = new Frame();
Frame.Client client;
frm.setLayout(null);
frm.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
frm.setResizable(false);
frm.setSize(1600,900);
frm.setVisible(true);
}
}
// get and send the Desktopimage
public class desktopCapture {
Robot robo;
BufferedImage screenImage;
Rectangle bounding;
public desktopCapture() {
try {
bounding = new Rectangle(0,0,1600,900);
robo = new Robot();
} catch (AWTException e) {e.printStackTrace();}
}
public void sendScreenCapture(Socket client) {
screenImage = robo.createScreenCapture(bounding);
try {
ImageIO.write(screenImage, "png", client.getOutputStream());
} catch (IOException e) {e.printStackTrace();}
}
}
// in Frame two function for actionListener Objects, so I can say who streams his Desktop and which get only the Images to.
public void readImage() {
while(true) {
try {
while((screenImage = ImageIO.read(in)) != null){
repaintScreen();
}
} catch (IOException e) {e.printStackTrace();}
}
}
public void sendImage() {
try {
while(true){
dC.sendScreenCapture(client);
System.out.println("read1");
while((screenImage = ImageIO.read(in)) != null){
System.out.println("read2");
ImageIO.write(screenImage, "png", new File("image1.png"));
Thread.sleep(250);
}
repaintScreen();
screenImage = null;
}
} catch (IOException | InterruptedException e) {e.printStackTrace();}
}
}
}
//Thread for a Client
public class handler implements Runnable {
Socket client;
OutputStream out;
InputStream in;
PrintWriter writer;
BufferedImage image;
public handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while(true) {
System.out.println("write1");
while((image = ImageIO.read(in)) != null){
System.out.println("write2");
for(int i = 1;i <= Server.connectionArray.size();i++){
Socket TEMP_SOCK = (Socket)Server.connectionArray.get(i-1);
out = TEMP_SOCK.getOutputStream();
writer = new PrintWriter(out);
ImageIO.write(image, "png", TEMP_SOCK.getOutputStream());
System.out.println("write3");
}
image = null;
}
}
} catch (IOException e) {e.printStackTrace();}
}
}
I would change your for loop to:
int count = Server.connectionArray.size()
int index = count - 1;
for(int i = 0;i < count; i++){
Socket TEMP_SOCK = (Socket)Server.connectionArray.get(index);
out = TEMP_SOCK.getOutputStream();
writer = new PrintWriter(out);
ImageIO.write(image, "png", TEMP_SOCK.getOutputStream());
System.out.println("write3");
}

Categories