[RESOLVIDO] Como salvar em um arquivo, em formato String, o que vem de um PrintWriter?

6 respostas
A

Olá galera,

estou querendo que a cada mensagem enviada, salvar a mensagem em um arquivo, em formato string.

Já tentei de várias formas, mas sempre salva em outro tipo de formato. Como o que tá abaixo. Alguém sabe como posso resolver isso?

java.util.Scanner[delimiters=\p{javaWhitespace}+][position=7][match valid=true][need input=false][source closed=false][skipped=false][group separator=\.][decimal separator=\,][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
public void salvarEmArquivoLog(String str) throws IOException {

		//CRIA UMA INSTANCIA DE FILE, CONVERTENDO A STRING EM UM CAMINHO
		File arquivo = new File("c:\\log.txt");

		//AQUI E VERIFICADO SE O ARQUIVO EXISTE
		if (!arquivo.exists()) {
			//SE O ARQUIVO NAO EXISTE ELE E CRIADO
			arquivo.createNewFile();
		}

		//CONSTROI UM OBJETO FILEWRITER, PASSANDO UM OBJETO FILE
		FileWriter fw = new FileWriter(arquivo, true);

		//CRTA UM BUFFER COM CARACTERES DE SAIDA
		BufferedWriter bw = new BufferedWriter(fw);

		//AQUI OS CARACTERES SAO GRAVADOS NO ARQUIVO
		bw.write(str);

		//AQUI E PRA SER INSERIDO UMA LINHA SEPARADORA (ESCREVE EM UMA NOVA LINHA)
		bw.newLine();

		bw.close();
		fw.close();

	}
@Override
    public void enviarMensagemParaCliente() throws Exception{
        Scanner teclado = new Scanner(System.in);
        PrintWriter saida = new PrintWriter(socketClient.getOutputStream());
        
        Log log = new Log();
        
        if(teclado.hasNextLine()){
            saida.println(teclado.nextLine());
            log.salvarEmArquivoLog(teclado.toString());
        }
        //teclado.close();
        saida.flush();
    }

6 Respostas

A

Fiz uma modificação mas agora a saída é outra, continua sem salvar em formato String.

Tá salvando como segue abaixo

java.io.PrintStream@47b480
@Override
    public void enviarMensagemParaCliente() throws Exception{
        Scanner teclado = new Scanner(System.in);
        PrintWriter saida = new PrintWriter(socketClient.getOutputStream());
        
        Log log = new Log();
        
        if(teclado.hasNextLine()){
            saida.println(teclado.nextLine());
            
            String str = saida.toString();
            
            log.salvarEmArquivoLog(str);
        }
        //teclado.close();
        saida.flush();
    }
F

veja

public void criaTxt(){       
            File arquivo = new File("/diretorio/arquivo.txt");
            if(arquivo.exists()){
                //se existir
                FileWriter arquivoTxt = new FileWriter(arquivo, true);
                PrintWriter linhasTxt = new PrintWriter(arquivoTxt);
                
                linhasTxt.println("linha1");
                linhasTxt.println("linha2");
                linhasTxt.println("linha3");
                
                arquivoTxt.close();
            }

t+ e boa sorte.

L

Vc ta gravando no log o toString() do PrintWriter, que deve ser mais ou menos isso java.io.PrintWriter@xxxxxxx. Acho que fazendo assim resolve pra vc.

if(teclado.hasNextLine()){ String line = teclado.nextLine(); // Pega a linha atual saida.println(line); // Manda a linha para o console log.salvarEmArquivoLog(line); // Manda a linha para o arquivo }

A

lsjunior:
Vc ta gravando no log o toString() do PrintWriter, que deve ser mais ou menos isso java.io.PrintWriter@xxxxxxx. Acho que fazendo assim resolve pra vc.

if(teclado.hasNextLine()){ String line = teclado.nextLine(); // Pega a linha atual saida.println(line); // Manda a linha para o console log.salvarEmArquivoLog(line); // Manda a linha para o arquivo }

Opa lsjunior, obrigado pela ajuda.

Apesar de estar salvando em formato String no arquivo, o estranho é que agora, quando eu digito algo na console do servidor-cliente e cliente-servidor, algumas mensagens não são enviadas e nem todas são salvas no arquivo.

Sem a implementação de arquivo, o sincronismo ocorre, um envia e o outro recebe.

A implementação de arquivos tá interfirindo no sincronismo das mensagens para enviar e receber.

L
Olha, fiz essa classe aqui para testar socket.
package br.com.guj.socket;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server implements Runnable {

	private static final String	LOG_FILE	= "/tmp/socket.txt";

	private static final int	PORT		= 9999;

	private boolean				run			= true;

	private ServerSocket		server;

	private OutputStream		outputStream;

	private PrintStream			printStream;

	@Override
	public void run() {
		try {
			System.out.println("Criando o socket na porta " + Server.PORT);
			this.outputStream = new FileOutputStream(Server.LOG_FILE);
			this.printStream = new PrintStream(this.outputStream);
			this.server = new ServerSocket(Server.PORT);

			while (this.run) {
				System.out.println("Aguardando uma conexao");
				Socket socket = this.server.accept();
				this.handle(socket);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (this.printStream != null) {
				this.printStream.close();
			}
			if (this.outputStream != null) {
				try {
					this.outputStream.close();
				} catch (IOException e) {
					//
				}
			}
		}

		try {
			this.server.close();
		} catch (IOException e) {
			//
		}
	}

	private void handle(final Socket socket) throws IOException {
		System.out.println("Conectado de " + socket.getLocalSocketAddress() + ":" + socket.getLocalPort());
		boolean loop = true;
		byte[] buffer = new byte[8192];
		InputStream inputStream = socket.getInputStream();
		OutputStream outputStream = socket.getOutputStream();

		do {
			if ((!socket.isClosed()) && (!socket.isInputShutdown()) && (!socket.isOutputShutdown())) {
				int len = inputStream.read(buffer);
				if (len > 0) {
					String msgIn = new String(buffer, 0, len).trim(); // Pega a mensagem
					String msgOut = "Bytes recebidos: " + len + "\n"; // Mensagem de retorno
					this.printStream.println(msgIn); // Grava no log
					System.out.println(msgIn); // Exibe no console
					outputStream.write(msgOut.getBytes()); // Retorna para o cliente a quantidade de bytes

					// Para fechar o socket
					if ((msgIn.equals("exit")) || (msgIn.equals("stop"))) {
						socket.shutdownInput();
						socket.shutdownOutput();
						socket.close();
						loop = false;
						if (msgIn.equals("stop")) {
							this.run = false;
						}
					}
				}
			} else {
				loop = false;
			}
		} while (loop);
	}

	public static void main(final String[] args) {
		Server server = new Server();
		Thread thread = new Thread(server);
		thread.start();
	}

}
Abaixo o shell do linux durante os testes:
[lourival@tsesedesc1-21 tmp]$ telnet localhost 9999
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Ola
Bytes recebidos: 5
Mais uma linha
Bytes recebidos: 16
testando
Bytes recebidos: 10
exit
Bytes recebidos: 6
Connection closed by foreign host.
[lourival@tsesedesc1-21 tmp]$ telnet localhost 9999
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Agora vai parar
Bytes recebidos: 17
stop
Bytes recebidos: 6
Connection closed by foreign host.
[lourival@tsesedesc1-21 tmp]$ cat /tmp/socket.txt 
Ola
Mais uma linha
testando
exit
Agora vai parar
stop
O console do Eclipse:
Criando o socket na porta 9999
Aguardando uma conexao
Conectado de /0:0:0:0:0:0:0:1:9999:9999
Ola
Mais uma linha
testando
exit
Aguardando uma conexao
Conectado de /0:0:0:0:0:0:0:1:9999:9999
Agora vai parar
stop
E o arquivo de log:
[lourival@tsesedesc1-21 tmp]$ cat /tmp/socket.txt 
Ola
Mais uma linha
testando
exit
Agora vai parar
stop
A
lsjunior:
Olha, fiz essa classe aqui para testar socket.
package br.com.guj.socket;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server implements Runnable {

	private static final String	LOG_FILE	= "/tmp/socket.txt";

	private static final int	PORT		= 9999;

	private boolean				run			= true;

	private ServerSocket		server;

	private OutputStream		outputStream;

	private PrintStream			printStream;

	@Override
	public void run() {
		try {
			System.out.println("Criando o socket na porta " + Server.PORT);
			this.outputStream = new FileOutputStream(Server.LOG_FILE);
			this.printStream = new PrintStream(this.outputStream);
			this.server = new ServerSocket(Server.PORT);

			while (this.run) {
				System.out.println("Aguardando uma conexao");
				Socket socket = this.server.accept();
				this.handle(socket);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (this.printStream != null) {
				this.printStream.close();
			}
			if (this.outputStream != null) {
				try {
					this.outputStream.close();
				} catch (IOException e) {
					//
				}
			}
		}

		try {
			this.server.close();
		} catch (IOException e) {
			//
		}
	}

	private void handle(final Socket socket) throws IOException {
		System.out.println("Conectado de " + socket.getLocalSocketAddress() + ":" + socket.getLocalPort());
		boolean loop = true;
		byte[] buffer = new byte[8192];
		InputStream inputStream = socket.getInputStream();
		OutputStream outputStream = socket.getOutputStream();

		do {
			if ((!socket.isClosed()) && (!socket.isInputShutdown()) && (!socket.isOutputShutdown())) {
				int len = inputStream.read(buffer);
				if (len > 0) {
					String msgIn = new String(buffer, 0, len).trim(); // Pega a mensagem
					String msgOut = "Bytes recebidos: " + len + "\n"; // Mensagem de retorno
					this.printStream.println(msgIn); // Grava no log
					System.out.println(msgIn); // Exibe no console
					outputStream.write(msgOut.getBytes()); // Retorna para o cliente a quantidade de bytes

					// Para fechar o socket
					if ((msgIn.equals("exit")) || (msgIn.equals("stop"))) {
						socket.shutdownInput();
						socket.shutdownOutput();
						socket.close();
						loop = false;
						if (msgIn.equals("stop")) {
							this.run = false;
						}
					}
				}
			} else {
				loop = false;
			}
		} while (loop);
	}

	public static void main(final String[] args) {
		Server server = new Server();
		Thread thread = new Thread(server);
		thread.start();
	}

}
Abaixo o shell do linux durante os testes:
[lourival@tsesedesc1-21 tmp]$ telnet localhost 9999
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Ola
Bytes recebidos: 5
Mais uma linha
Bytes recebidos: 16
testando
Bytes recebidos: 10
exit
Bytes recebidos: 6
Connection closed by foreign host.
[lourival@tsesedesc1-21 tmp]$ telnet localhost 9999
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Agora vai parar
Bytes recebidos: 17
stop
Bytes recebidos: 6
Connection closed by foreign host.
[lourival@tsesedesc1-21 tmp]$ cat /tmp/socket.txt 
Ola
Mais uma linha
testando
exit
Agora vai parar
stop
O console do Eclipse:
Criando o socket na porta 9999
Aguardando uma conexao
Conectado de /0:0:0:0:0:0:0:1:9999:9999
Ola
Mais uma linha
testando
exit
Aguardando uma conexao
Conectado de /0:0:0:0:0:0:0:1:9999:9999
Agora vai parar
stop
E o arquivo de log:
[lourival@tsesedesc1-21 tmp]$ cat /tmp/socket.txt 
Ola
Mais uma linha
testando
exit
Agora vai parar
stop

lsjunior, a sua primeira resposta já foi o suficiente. Eu apenas tinha me confundido e além da modificação que vc colocou, eu esqueci de comentar uma linha. Aí por isso que tinham mensagens que não estavam sendo enviadas e outras não estavam sendo salvas no arquivo.

Obrigado!

Criado 10 de novembro de 2011
Ultima resposta 11 de nov. de 2011
Respostas 6
Participantes 3