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); } }