J2EE Part 16

1.下載檔案
SimpleServer.java  (01_download_file)

import java.net.*;
import java.io.*;

public class SimpleServer {
  public static void main ( String args [ ] ){
    ServerSocket s = null;

    try {
      s = new ServerSocket ( 5433 );
    } catch ( IOException e ){
      e.printStackTrace();
    }

    while ( true ){
      try{
        Socket s1 = s.accept();
        OutputStream s1out = s1.getOutputStream();
//        BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(s1out) );
//        bw.write( "Hello Net World! I am the teacher winjow!\n" );
        FileInputStream fis = new FileInputStream("libertytimes.htm");
        int data =0;
        while ( (data =fis.read()) != -1 ){
          s1out.write(data);
        }
// bw.close();
s1.close();
fis.close();
      } catch ( IOException e ){
e.printStackTrace();
      }
    } // while
  } // main
} // class


SimpleClient.java

import java.net.*;
import java.io.*;

public class SimpleClient{
  public static void main( String[] args ){
    try{
      Socket s1 = new Socket("192.168.2.168", 5433);

      InputStream is = s1.getInputStream();
//      InputStreamReader isr = new InputStreamReader( is );
//      BufferedReader br = new BufferedReader( isr );
//      System.out.println( br.readLine() );
      FileOutputStream fos = new FileOutputStream("test2.htm");
      int data =0;
      while ( (data = is.read()) !=-1 ){
        fos.write(data);
      }

//      br.close();
      fos.close();
      s1.close();
    } catch ( ConnectException connExc ){
      System.err.println( "Could not connect." );
    } catch ( IOException e ){
      System.out.println(e);
    }
  } //main()
} //class


2.Try...Catch
範例一 (02_try_catch_ex):
test.java

public class Test {
  public static void main ( String[] args ){
    Human h01 = new Human();
    try {
      h01.setLegs(-1);
    } catch (IllegalArgumentException e){
      System.out.print(e);
    } catch (Exception e ){
      System.out.print(e);
    }
    System.out.println( ", " +h01.getLegs() );
  }
}

human.java

public class Human {
  String name;
  private byte legs=2;

  public void setLegs(int legs){
    if ( legs >=0 ){
      this.legs = (byte)legs;
    } else {
      throw new IllegalArgumentException("腿數: " +legs);
    }
  }
  public byte getLegs(){
    return legs;
  }
}

run.bat

del *.class
javac *.java
java -cp . Test
pause

結果:


範例二 (03_try_catch_ex2
test.java


public class Test {
  public static void main ( String[] args ){
    int a=10, b=0, c=0;
    try {
      c = a/b;
      System.out.println( c );
    } catch (Exception e ){
      System.out.println("別鬧了! 分母怎會是: " +b);
    }
    System.out.println();
    System.out.println("程式結束!");
  }
}

run.bat

del *.class
javac *.java
java -cp . Test
pause

結果:

No comments: