当前页面: 开发资料首页 → Java 专题 → 菜鸟初学Java的备忘录(五)
摘要: 菜鸟初学Java的备忘录(五)
try{
}catch(ExceptionType1 e){
file://对异常情况1的处理
}catch(ExceptionType2 e){
file://对异常情况2的处理
throw(e)//抛出异常,和Delphi中的raise是一回事
}
import java.io.*;//调入和io相关的类第二个例子是一个存储电话信息的小程序,用户输入姓名和电话号码,程序将其存入phone.numbers文件中,通过FileOutputStream来实现
class fileinfo{
file://注意,main函数一定是静态方法
public static void main(String args【】)throws IOException{
File fileToCheck;//使用文件对象创建实例
if (args.length>0){
for (int i=0;ifileToCheck=new File(args【i】);//为文件对象分配空间
info(fileToCheck);//这里引用的info一定要是静态方法成员
}
}
else{
System.out.println("no file given");
}
}
public static void info(File f)throws IOException{
System.out.println("Name:"+f.getName());
System.out.println("Path:"+f.getPath());
if (f.exists()){
System.out.println("File exists.");
System.out.print((f.canRead()?" and is Readable":""));//判断函数,如果满足条件,输出前者,否则输出后者
System.out.print((f.canWrite()?"and is Writable":""));
System.out.print(".");
System.out.println("File is"+f.length()+"bytes.");
}
else{
System.out.println("File does not exist.");
}
}
}
import java.io.*;
class phones{
static FileOutputStream fos;
public static final int lineLength=81;
public static void main(String args[])throws IOException{
byte[] phone=new byte[lineLength];
byte[] name=new byte[lineLength];
int i;
fos=new FileOutputStream("phone.numbers");
while(true){
System.err.println("Enter a name(enter 'done' to quit)");
readLine(name);
if ("done".equalsIgnoreCase(new String(name,0,0,4))){
break;
}
System.err.println("Enter the phone number");
readLine(phone);
for (i=0;phone[i]!=0;i++){
fos.write(phone[i]);
}
fos.write(',');
for (i=0;name[i]!=0;i++){
fos.write(name[i]);
}
fos.write('\n');
}
fos.close();
}
private static void readLine(byte line[])throws IOException{
int i=0,b=0;
while((i<(lineLength-1))&&((b=System.in.read())!='\n')){
line[i++]=(byte)b;
}
line[i]=(byte)(0);
}
}
import java.net.*;//java.net 包提供套接字工具。
public class RemoteFileClient {
protected String hostIp;
protected int hostPort;
protected BufferedReader socketReader;//负责读数据的对象
protected PrintWriter socketWriter;//负责写数据的对象
file://类的构造器有两个参数:远程主机的 IP 地址(hostIp)和端口号(hostPort)各一个.构造器将它们赋给实例变量
public RemoteFileClient(String aHostIp, int aHostPort) {
hostIp = aHostIp;
hostPort = aHostPort;
}
public static void main(String[] args) {
}
file://连接到远程服务器
public void setUpConnection() {
}
file://向远程服务器请求文件信息
public String getFile(String fileNameToGet) {
}
file://从远程服务器上断开
public void tearDownConnection() {
}
}
public void setUpConnection() {
try {
Socket client = new Socket(hostIp, hostPort);//创建Socket对象
OutputStream outToServerStream=client.getOutputStream();
InputStream inFromServerStream=client.getInputStream();
socketReader = new BufferedReader(new InputStreamReader(inFromServerStream));
file://把Socket的InputStream包装进BufferedReader 以使我们能够读取流的行
socketWriter = new PrintWriter(outToServerStream);
file://把Socket的OutputStream包装进PrintWriter 以使我们能够发送文件请求到服务器
} catch (UnknownHostException e) {
System.out.println("Error setting up socket connection: unknown host at " + hostIp + ":" + hostPort);
file://对Socket对象创建错误的异常处理
} catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
file://对IO错误的异常处理
}
}
public String getFile(String fileNameToGet) {
StringBuffer fileLines = new StringBuffer();//StringBuffer对象也是String对象,但是比它更灵活,这里是用来存放读取内容的
try {
socketWriter.println(fileNameToGet);
socketWriter.flush();//文件存放地址输出到socketWriter中,然后清空缓冲区,让这个地址送到服务器中去
String line = null;
while ((line = socketReader.readLine()) != null)
fileLines.append(line + "\n");
file://既然已经发送到服务器去了,那我们都要等待响应,这里的程序就是等待服务器把我们所需要的文件内容传过来
} catch (IOException e) {
System.out.println("Error reading from file: " + fileNameToGet);
}
return fileLines.toString();//别忘了把buffer中的内容转成String再返回
}
3.断开
public void tearDownConnection() {
try {
socketWriter.close();
socketReader.close();
} catch (IOException e) {
System.out.println("Error tearing down socket connection: " + e);
}
}
import java.io.*;
import java.net.*;
public class RemoteFileClient {
protected BufferedReader socketReader;
protected PrintWriter socketWriter;
protected String hostIp;
protected int hostPort;
public RemoteFileClient(String aHostIp, int aHostPort) {
hostIp = aHostIp;
hostPort = aHostPort;
}
public String getFile(String fileNameToGet) {
StringBuffer fileLines = new StringBuffer();
try {
socketWriter.println(fileNameToGet);
socketWriter.flush();
String line = null;
while ((line = socketReader.readLine()) != null)
fileLines.append(line + "\n");
} catch (IOException e) {
System.out.println("Error reading from file: " + fileNameToGet);
}
return fileLines.toString();
}
public static void main(String[] args) {
RemoteFileClient remoteFileClient = new RemoteFileClient("127.0.0.1", 3000);
remoteFileClient.setUpConnection();
String fileContents = remoteFileClient.getFile("RemoteFile.txt");
remoteFileClient.tearDownConnection();
System.out.println(fileContents);
}
public void setUpConnection() {
try {
Socket client = new Socket(hostIp, hostPort);
OutputStream outToServerStream=client.getOutputStream();
InputStream inFromServerStream=client.getInputStream();
socketReader = new BufferedReader(new InputStreamReader(inFromServerStream));
socketWriter = new PrintWriter(outToServerStream);
} catch (UnknownHostException e) {
System.out.println("Error setting up socket connection: unknown host at " + hostIp + ":" + hostPort);
} catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
}
}
public void tearDownConnection() {
try {
socketWriter.close();
socketReader.close();
} catch (IOException e) {
System.out.println("Error tearing down socket connection: " + e);
}
}
}
import java.io.*;跟客户机中一样,首先导入 java.net 的 java.io。接着,给我们的类一个实例变量以保存端口,我们从该端口侦听进入的连接。缺省情况下,端口是 3000。
import java.net.*;
public class RemoteFileServer {
protected int listenPort = 3000;
public static void main(String[] args) {
}
public void acceptConnections() {
}
public void handleConnection(Socket incomingConnection) {
}
}
public static void main(String[]args) {非常简单,因为主函数无非是让服务器进入监听状态,所以直接调用acceptConnection().需要注意的是,必须先创建RemoteFileServer()的实例,而不是直接调用.
RemoteFileServer server = new RemoteFileServer();
server.acceptConnections();
}
public void acceptConnections() {
try {
ServerSocket server = new ServerSocket(listenPort);//同客户机的Socket对应,在服务器端,我们需要ServerSocket对象,参数是兼听的端口号
Socket incomingConnection = null;//创建一个客户端的Socket变量,以接收从客户端监听到的Socket
while (true) {
incomingConnection = server.accept();//调用该 ServerSocket 的 accept() 来告诉它开始侦听,
handleConnection(incomingConnection);
}
file://不断监听直到来了一个连接请求,然后交由handleConnection处理
} catch (BindException e) {
System.out.println("Unable to bind to port " + listenPort);
} catch (IOException e) {
System.out.println("Unable to instantiate a ServerSocket on port: " + listenPort);
}
}
public void handleConnection(Socket incomingConnection) {
try {
OutputStream outputToSocket = incomingConnection.getOutputStream();
InputStream inputFromSocket = incomingConnection.getInputStream();
file://首先获取同Socket相关联的流outputToSocket和InputStream
file://其中outputToSocket是要返回给客户端Socket的流
file://InputStream是客户端发来的请求,在这里就是文件路径,即"RemoteFile.txt"
BufferedReader streamReader =
new BufferedReader(new InputStreamReader(inputFromSocket));
file://首先要将InputStream转换到BufferedReader中
FileReader fileReader = new FileReader(new File(streamReader.readLine()));
file://从BufferedReader中读出文件路径,建立新对象FileReader
BufferedReader bufferedFileReader = new BufferedReader(fileReader);
file://再次建立BufferedReader对象,这一次它读取得是文件里面的内容
PrintWriter streamWriter =
new PrintWriter(OutputStream);
file://把Socket的outputToSocket流包装进PrintWriter 以使我们能够发送文件信息到客户端
String line = null;
while ((line = bufferedFileReader.readLine()) != null) {
streamWriter.println(line);
}
file://从bufferedFileReader中读出文件信息,再经由streamWriter输出到客户端
fileReader.close();
streamWriter.close();//注意Socket的两个流关闭的顺序
streamReader.close();
file://完成之后关闭所有流
} catch (Exception e) {
System.out.println("Error handling a client: " + e);
}
}
import java.io.*;
import java.net.*;
public class RemoteFileServer {
int listenPort;
public RemoteFileServer(int aListenPort) {
listenPort = aListenPort;
}
public void acceptConnections() {
try {
ServerSocket server = new ServerSocket(listenPort);
Socket incomingConnection = null;
while (true) {
incomingConnection = server.accept();
handleConnection(incomingConnection);
}
} catch (BindException e) {
System.out.println("Unable to bind to port " + listenPort);
} catch (IOException e) {
System.out.println("Unable to instantiate a ServerSocket on port: " + listenPort);
}
}
public void handleConnection(Socket incomingConnection) {
try {
OutputStream outputToSocket = incomingConnection.getOutputStream();
InputStream inputFromSocket = incomingConnection.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputFromSocket));
FileReader fileReader = new FileReader(new File(streamReader.readLine()));
BufferedReader bufferedFileReader = new BufferedReader(fileReader);
PrintWriter streamWriter = new PrintWriter(outputToSocket);
String line = null;
while ((line = bufferedFileReader.readLine()) != null) {
streamWriter.println(line);
}
fileReader.close();
streamWriter.close();
streamReader.close();
} catch (Exception e) {
System.out.println("Error handling a client: " + e);
}
}
public static void main(String[] args) {
RemoteFileServer server = new RemoteFileServer(3000);
server.acceptConnections();
}
}