直接在这里总结,IO的两种方式,字符流和字节流,当然后面要核对一下对不对,或者有没有更好的。
字符流
import java.io.*;
import java.net.*;
public class Test
{
public static void main(String[] args) throws Exception
{
//字节流输入,以Socket.getInputStream()为例
Socket socket = new Socket(ip,port);
InputStream input = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String line = br.readLine();
br.close();
socket.close();
//字节流输出,也以Socket.getOutputStream()为例
Socket socket = new Socket(ip,port);
OutputStream output = socket.getOutputStream();
PrintStream ps = new PrintStream(output);
ps.println("您好,您收到了服务器的新年祝福!");
ps.close();
socket.close();
}
}
字节流
import java.io.*;
import java.net.*;
public class Test
{
public static void main(String[] args) throws Exception
{
//都是以Socket为例
//字节流输入
Socket socket = new Socket(ip,port);
InputStream input = socket.getInputStream();
byte[] buffer = new byte[1024];
int hasRead = -1;
int length = 0;
while((hasRead = input.read(buffer)) != -1)
{
System.out.println(new String(buffer, "utf-8");
}
input.close();
socket.close();
//字节流输出
Socket socket = new Socket(ip,port);
OutputStream output = socket.getOutputStream();
output.write(buffer);
//补充一个本机上的字节流的输入
try(
RandomAccessFile raf = new RandomAccessFile("","r"))
{
byte[] buffer = new byte[1024];
int hasRead = -1;
int length = 0;
while((hasRead = raf.read(buffer)) != -1)
{
System.out.println(new String(buffer,"utf-8");
}
}
catch(Exception e)
{
e.printStackTrace();
}
//补充一个本机上的字节流的输出
try(
RandomAccessFile raf = new RandomAccessFile("","rw"))
{
raf.write("Hello World!".getBytes());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}