import java.io.*;//调入和io相关的类 class fileinfo{ file://注重,main函数一定是静态方法
public static void main(String args[])throws IOException{ File fileToCheck;//使用文件对象创建实例 if (args.length>0){ for (int i=0;i<args.length;i++){ fileToCheck=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."); } } }
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(′ ′); } fos.close(); }
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) { RemoteFileServer server = new RemoteFileServer(); server.acceptConnections(); } 非常简单,因为主函数无非是让服务器进入监听状态,所以直接调用acceptConnection().需要注重的是,必须先创建RemoteFileServer()的实例,而不是直接调用.
那么服务器是怎样通过acceptConnection()来监听客户机的连接呢?并且假如兼听到了,又怎样处理呢?我们来看 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); } }