PrintWriter和BufferedWriter都是继承java.io.Writer,所以很多功能都一样。不过PrintWriter提供println()方法可以写不同平台的换行符,而BufferedWriter可以任意设定缓冲大小。
OutputStream可以直接传给PrintWriter(BufferedWriter不能接收),如:
PrintWriter out
= new PrintWriter(new BufferedOutputStream(new FileOutputStream( "foo.out ")));
或者用OutputStreamWriter来将OutputStream转化为Writer.这时就可以用BufferedWriter了。
参考下TCP通信
class Tcpserver {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(9999);
Socket st= s.accept();
//读取 socket读取流中的数据。
BufferedReader br = new
BufferedReader(new InputStreamReader(st.getInputStream()));
//目的,socket输出流,将大写数据写入到socket,并发送给客户端
/*BufferedWriter bw =new
BufferedWriter(new OutputStreamWriter(st.getOutputStream()));
*/
PrintWriter pw = new PrintWriter(st.getOutputStream(),true);
String len = null;
while((len = br.readLine())!=null){
/* bw.write(len.toUpperCase());
bw.newLine();
bw.flush();*/
pw.println(len.toUpperCase());
}
st.close();
s.close();
}
}
public class TcpSocket {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("192.168.1.104",9999);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// BufferedWriter inbw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
BufferedReader inbr = new BufferedReader(new InputStreamReader(s.getInputStream()));
String len = null;
while((len = br.readLine())!=null){
if("over".equals(len))
break;
pw.println(len);
/* inbw.write(len);
inbw.newLine();
inbw.flush();*/
String str=inbr.readLine();
System.out.println("server..."+str);
}
s.close();
br.close();
}
}
|