getOutputStream 메서드를 사용하여 어떻게 strin을 보낼 수 있습니까? 언급 한대로 바이트 만 보낼 수 있습니다. 지금까지 바이트를 보낼 수 있습니다. 그러나 문자열 값은 아닙니다.
public void sendToPort() throws IOException {
Socket socket = null;
try {
socket = new Socket("ip address", 4014);
socket.getOutputStream().write(2); // have to insert the string
} catch (UnknownHostException e) {
System.err.print(e);
} finally {
socket.close();
}
}
미리 감사드립니다
PrintWriter를 사용하는 방법 :
OutputStream outstream = socket .getOutputStream();
PrintWriter out = new PrintWriter(outstream);
String toSend = "String to send";
out.print(toSend );
편집 : 내 대답을 찾았고 개선 사항이 논의되었지만 생략되었습니다. OutputStreamWriter를 사용하여 문자열을 작성하는 더 좋은 방법은 다음과 같습니다 .
// Use encoding of your choice
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir), "UTF8"));
// append and flush in logical chunks
out.append(toSend).append("\n");
out.append("appending more before flushing").append("\n");
out.flush();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다