0

I have a working system here which communicates my android client to my Java Server. Basically it just send a message by my android client and my server receives it by System.out.println(message); . Now what I want to happen is to save all receives message to a single textfile that will serve as my logs and it will update as soon as my server receives a new message.

while ((message = bufferedReader.readLine()) != null) {
                    System.out.println("Message from " + message + " at " + dateFormat.format(cal.getTime()));
                    str.append(message+"\n");


                }

This one is a part of my Java Serve code. BTW I am using TCP port to communicate my server and my client thru the same network. I want to save to a textfile the text that is holded by the str string. How can I do that? Or is that possible? Thanks in advance!

Kindly check out my code:

PrintWriter out= new PrintWriter(new BufferedWriter(new FileWriter("C:/foo.txt")));
                while ((message = bufferedReader.readLine()) != null) {
                    System.out.println("Message from " + message + " at " + dateFormat.format(cal.getTime()));
                    str.append(message+"\n");
                    out.println(message);


                }
Kerv
  • 179
  • 1
  • 5
  • 15

1 Answers1

1

One easy way to achieve file output is to run the Server code with an output redirection

java -cp<Whatever classpath> ServerClassName >file & 

If you need to write to a file from java, you can use following pseudo code

PrintWriter out= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
while ( read message as you doing now)  {
    // do something 
    out.println(message);
    // do something
}
Akhilesh Singh
  • 2,548
  • 1
  • 13
  • 10