Refreshing a document - java

I have a writing/reading .txt files program, which I will put at the bottom so I can ask my question first: Usually, if I have the file open and run the program, I need to close the .txt file and reopen it in order to see the changes the program makes. Is there a way to refresh the document in the program so that It will change before my eyes in real time? Here is the program:
package SingleThings;
import java.io.*;
public class TextUtil {
public String path;
public String[] lines;
public TextUtil(String pathy,int length){
path=pathy;
makeFile();
lines = new String[length];
for(int i = 0;i<length;i++){
lines[i]=getLine(i+1);
}
}
public void clear(){
try{
FileWriter write = new FileWriter(path , false);
}catch(IOException e){
System.out.println("There was a problem oh noesss " + e);
}
}
private void makeFile(){
try {
File file = new File(path);
if (file.createNewFile()){
System.out.println("Creating file...");
}else{
System.out.println("Loading file...");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String getLine(int line){
BufferedReader in;
String read = null;
int linenum = line;
try {
in = new BufferedReader(new FileReader(path));
while(linenum > 0){
read = in.readLine();
linenum--;
}
in.close();
return read;
}catch(IOException e){
System.out.println("There was a problem:" + e);
return "error";
}
}
private void write(String text){
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(path,true));
out.write(text);
out.newLine();
out.close();
}catch(IOException e){
System.out.println("There was a problem:" + e);
}
}
public void update(){
clear();
for(int i=0;i<lines.length;i++){
if(lines[i]!=null){
write(lines[i]);
}else{
write("");
}
}
}
}

Related

Client/Server Chat app with file transfer JAVA Sockets

I am new to java and I made a chat application through which client and server can send and receive messages, now I was trying to send a file from client to server but after the file is received by server , client and server both cant send messages , Here is the code :
Client Side :
import java.io.*;
import java.net.*;
import javax.swing.JFileChooser;
public class ClientFrame extends javax.swing.JFrame {
static Socket s;
static DataOutputStream dos1;
static DataInputStream dis;
static javax.swing.JTextArea jT;
static JFileChooser fc = new JFileChooser();
File file;
public ClientFrame() {
initComponents();
jT = jTextArea1;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//send message
try {
String str1 = jTextField1.getText();
String o = jT.getText() + "\n" + " Client ->" + str1;
jT.setText(o);
dos1.writeUTF(str1);
} catch (Exception ex) {
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//open file chooser
fc.showOpenDialog(this);
file = fc.getSelectedFile();
jTextField3.setText(file.getAbsolutePath());
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//send file
try {
String st = jT.getText() + "\n" + " Client -> " + "Sending a file";
jT.setText(st);
String str1 = "Client Sending a file,Press 'REC File' ";
String st1 = "\n" + " Client ->" + str1;
dos1.writeUTF(st1);
} catch (Exception e) {
}
long length = file.length();
byte[] bytes = new byte[65536];//65536 is max, i think
InputStream in;
try {
in = new FileInputStream(file);
OutputStream out = s.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
s_r_m();
} catch (Exception ex) {
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClientFrame().setVisible(true);
}
});
try {
s = new Socket("localhost", 3000);
} catch (Exception e) {
}
s_r_m();
}
public static void s_r_m() {
System.out.println("call srm");
try {
dis = new DataInputStream(s.getInputStream());
dos1 = new DataOutputStream(s.getOutputStream());
while (true) {
String str = (String) dis.readUTF();
String out = jT.getText() + "\n" + " Server ->" + str;
jT.setText(out);
}
} catch (Exception ex) {
}
}
}
Server Side :
import java.io.*;
import java.net.*;
import javax.swing.JFileChooser;
public class ServerFrame extends javax.swing.JFrame {
static ServerSocket ss;
static Socket s;
static DataInputStream dis;
static DataOutputStream dos1;
static javax.swing.JTextArea jT;
static JFileChooser fc = new JFileChooser();
File file;
public ServerFrame() {
initComponents();
jT = jTextArea1;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//send message
try {
String str1 = jTextField1.getText();
String out = jT.getText() + "\n" + " Server ->" + str1;
jT.setText(out);
dos1.writeUTF(str1);
} catch (Exception ex) {
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//open file chooser
fc.showOpenDialog(this);
file = fc.getSelectedFile();
jTextField3.setText(file.getAbsolutePath());
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
//rec file
InputStream in = null;
OutputStream out = null;
try {
in = s.getInputStream();
out = new FileOutputStream("F:\\yoMama.exe");
int count;
byte[] buffer = new byte[65536];
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
String o = jT.getText() + "\n" + " Client ->" + " File received";
jT.setText(o);
out.close();
in.close();
s_r_m();
} catch (Exception ex) {
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ServerFrame().setVisible(true);
}
});
try {
ss = new ServerSocket(3000);
s = ss.accept();//will accept connection from client,waiting state untill client connects
s_r_m();
} catch (Exception e) {
}
}
public static void s_r_m() {
System.out.println("call srm");
try {
dis = new DataInputStream(s.getInputStream());
dos1 = new DataOutputStream(s.getOutputStream());
while (true) {
String str = dis.readUTF();
String out = jT.getText() + "\n" + " Client ->" + str;
jT.setText(out);
}
} catch (Exception ex) {
}
}
}
The problem is in the s_r_m() function. In while loop first statement is String str = dis.readUTF(); So here both Client and Server will wait for the reply from the other side first which will end up in a Deadlock. So Any of them won't be able to send any data till the receive from the other side.
So there you need to change code accordingly. I have implemented a code to solve this problem which takes input from Key-Board(STDIN).
DataInputStream dis=new DataInputStream(sckt.getInputStream());
DataInputStream dis1=new DataInputStream(System.in);
DataOutputStream dos=new DataOutputStream(sckt.getOutputStream());
String str="";
while(true)
{
while(dis.available()>0) //If input is available from the other side.
{
String out = jT.getText() + "\n" + " Client ->" + dis.readUTF();
jT.setText(out);
}
while(dis1.available()>0) //If input is available from STDIN to send it to the other side.
{
str=sc.nextLine();
dos.writeUTF(str);
dos.flush();
}
}
Here you can change code of taking input from STDIN to Text-Field you have in your application. So Whenever a user press Send Button , It will send the message to the other side.

FileStreaming Saved File

This section of the code is not working. I'm trying to display the name saved in the file when the user has clicked n==1 into the textfield when the user has clicked n==0. It comes out blank for some reason I can't figure. Maybe I'm not calling the savedName return value properly?
if (n == 1){
for(fn=JOptionPane.showInputDialog("What is your first name?");!fn.matches("[a-zA-Z]+");fn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
fn=JOptionPane.showInputDialog("What is your first name?");
}
writeToFile();
for(sn=JOptionPane.showInputDialog("What is your second name?");!sn.matches("[a-zA-Z]+");sn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
sn=JOptionPane.showInputDialog("What is your second name?");
}
if (n == 0){
String fullName = readFromFile();
text.setText("Welcome " + fullName + ".");
System.out.println(fullName);
}
}
private void writeToFile() {
String nameToWrite = fn;
OutputStream outStream = null;
//String savedName = "";
try {
outStream = new FileOutputStream(f);
outStream.write(nameToWrite.getBytes());
//BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
//savedName = br.readLine();
text.setText("Welcome " + fn + ".");
//System.out.println(savedName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
// do nothing
}
}
}
//return savedName;
}
private String readFromFile(){
String savedName="";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
savedName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return savedName;
}

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");
}

Sending image Through TCP Socket in Java

I'm trying to make a Client Server Application which the server list name of available images and the client select one of them to download Such as here :
Thread in Server
public void run()
{
try {
in = new DataInputStream (server.getInputStream());
out = new DataOutputStream(server.getOutputStream());
out.writeUTF("To List images write list");
out.writeUTF("To Exit write 2");
out.flush();
while((line = in.readUTF()) != null && !line.equals("2")) {
if(line.equalsIgnoreCase("list"))
{
String [] images= processor.listImages();
for ( int i=0;i<images.length;i++) {
out.writeUTF((+1)+"-"+images[i]);
out.flush();
line = "";
}
out.writeUTF("-1");
line = in.readUTF();
if(line.equalsIgnoreCase("2"))
{
break;
}else
{
BufferedImage img =processor.processInput(line);
boolean cc = ImageIO.write(img,"JPG",server.getOutputStream());
if(!cc)
{
out.writeUTF("The entered image is not avaliable !");
}else
{
System.out.println("Image Sent");
}
}
}else if(line.equalsIgnoreCase("2")){
break;
}
}
try{
in.close();
out.close();
server.close();
}catch(Exception e){
System.out.println("Error : "+ e.getMessage());
}
} catch (IOException e) {
System.out.println("IOException on socket listen: " + e.getMessage());
}
}
Client :
public void start() throws IOException
{
String line="";
while(true)
{
try{
line = inputFromStream.readUTF();
System.out.println(line);
line = inputFromStream.readUTF();
System.out.println(line);
line = readFromConsol.readLine();
writeToStream.writeUTF(line);
if(line.equalsIgnoreCase("2")){
break;
}else if(line.equalsIgnoreCase("list")){
boolean check=true;
while(check){
line = inputFromStream.readUTF();
System.out.println(line);
if("-1".equals(line)) {
check=false;
}
}
line = readFromConsol.readLine();
if(line.equalsIgnoreCase("2")) {
break;
}else
{
writeToStream.writeUTF(line);
BufferedImage img=ImageIO.read(
ImageIO.createImageInputStream(client.getInputStream()));
File f = new File("E:/MyFile.png");
f.createNewFile();
ImageIO.write(img, "PNG", f);
//process.saveImage(tmp);
System.out.println("Saved");
}
}
}catch(Exception e)
{
System.out.println(e);
break;
}
}
try{
inputFromStream.close();
readFromConsol.close();
writeToStream.close();
this.client.close();
}catch(Exception e){
System.out.println("Error : "+e.getMessage());
}
}
The problem is that all commands are successfully submitted till image receiving image stop there doesn't move
Try doing a flush of the outstream on the sending socket, then close the socket.
The problem appears to be that until the socket is flushed and closed the receiving IOImage.read() will wait thinking there are more images in the stream.

Swing problem!(problem in showing a frame)

sorry for posting a lot of code!!I don't know that why my ListFrame doesn't work???
these are the classes.At first I run the MainServer and then I will run the MainFrame in the other package.and then by inserting a correct user name and password ,the Listframe will be shown,BUT I click on menu bar or list or delete button but nothing will happen.why?? please help me.
MainSerevr class :
public class MainServer {
static Socket client = null;
static ServerSocket server = null;
public static void main(String[] args) {
System.out.println("Server is starting...");
System.out.println("Server is listening...");
try {
server = new ServerSocket(5050);
} catch (IOException ex) {
System.out.println("Could not listen on port 5050");
System.exit(-1);
}
try {
client = server.accept();
System.out.println("Client Connected...");
} catch (IOException e) {
System.out.println("Accept failed: 5050");
System.exit(-1);
}
try {
BufferedReader streamIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean done = false;
String line;
while (!done) {
line = streamIn.readLine();
if (line.equalsIgnoreCase(".bye")) {
done = true;
} else {
System.out.println("Client says: " + line);
}
}
streamIn.close();
client.close();
server.close();
} catch (IOException e) {
System.out.println("IO Error in streams " + e);
}
}}
ListFrame:
public class ListFrame extends javax.swing.JFrame implements PersonsModelChangeListener {
private InformationClass client;
private static DefaultListModel model = new DefaultListModel();
private ListSelectionModel moDel;
/** Creates new form ListFrame */
public ListFrame(InformationClass client) {
initComponents();
this.client = client;
jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fillTable();
Manager.addListener(this);
}
private void deleteAPerson() {
int index = jList1.getSelectedIndex();
String yahooId = (String) jList1.getSelectedValue();
model.remove(index);
Manager.removeApersonFromSQL(yahooId);
int size = model.getSize();
if (size == 0) {
jButton1.setEnabled(false);
} else {
if (index == size) {
index--;
}
jList1.setSelectedIndex(index);
jList1.ensureIndexIsVisible(index);
}
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
AddAPerson frame = new AddAPerson(client);
frame.setVisible(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
deleteAPerson();
}
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
MainClient.setText("");
MainClient.runAClient();
ChatFrame frame = new ChatFrame(client);
frame.setVisible(true);
}
public void fillTable() {
try {
List<InformationClass> list = null;
list = Manager.getClientListFromMySQL();
if (list == null) {
JOptionPane.showMessageDialog(this, "You should add a person to your list", "Information", JOptionPane.OK_OPTION);
return;
} else {
for (int i = 0; i < list.size(); i++) {
InformationClass list1 = list.get(i);
model.add(i, list1.getId());
}
jList1.setModel(model);
}
} catch (SQLException ex) {
Logger.getLogger(ListFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
MainClient class:
public class MainClient {
private static InformationClass info = new InformationClass();
private static Socket c;
private static String text;
public static String getText() {
return text;
}
public static void setText(String text) {
MainClient.text = text;
}
private static PrintWriter os;
private static BufferedReader is;
static boolean closed = false;
/**
* #param args the command line arguments
*/
public static void runAClient() {
try {
c = new Socket("localhost", 5050);
os = new PrintWriter(c.getOutputStream());
is = new BufferedReader(new InputStreamReader(c.getInputStream()));
String teXt = getText();
os.println(teXt);
if(c!=null&& is!=null&&os!=null){
String line = is.readLine();
System.out.println("Text received: " + line);
}
c.close();
is.close();
os.close();
} catch (UnknownHostException ex) {
System.err.println("Don't know about host");
} catch (Exception e) {
System.err.println("IOException: " + e);
}
}
}
EDIT:I have found the problem,which is because of writting MainClient.runAClient() in code ,where should I put it? please help me.
This article contains an sscce that illustrates a simple client-server GUI. You may find it instructive. If so, consider how you would address the bug found in the last line of the Echo(Kind kind) constructor.

Categories