欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

java中基礎(chǔ)知識(shí)的示例分析

這篇文章主要為大家展示了“java中基礎(chǔ)知識(shí)的示例分析”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“java中基礎(chǔ)知識(shí)的示例分析”這篇文章吧。

靈璧ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來(lái)市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!

一.異常
Java對(duì)異常的處理同Delphi一樣,不是刻意的去避免它的發(fā)生,而是等它發(fā)生后去補(bǔ)救.
Delphi的異常處理簡(jiǎn)單來(lái)說(shuō)就是一下語(yǔ)句

Try
Except//異常發(fā)生后就轉(zhuǎn)入此處執(zhí)行
Finally//不管異常發(fā)不發(fā)生,都轉(zhuǎn)入此處運(yùn)行
End

與此相類似,Java的異常處理的基本形式如下
try{
}catch(ExceptionType1 e){
file://對(duì)異常情況1的處理
}catch(ExceptionType2 e){
file://對(duì)異常情況2的處理
throw(e)//拋出異常,和Delphi中的raise是一回事
}

要補(bǔ)充的是,對(duì)大多數(shù)的異常,假如你要在正常運(yùn)行的程序中而不是捕捉異常的程序中明確的拋出,Java的編譯器需要你事先對(duì)你要拋出的異常作聲明,否則不允許編譯通過(guò).這個(gè)任務(wù)是由throws來(lái)完成的.

二.Java的輸入輸出流
2.1 輸出
System.out.print  file://這里out是一個(gè)靜態(tài)方法哦
System.out.println
System.err.print  file://err和out一樣也是標(biāo)準(zhǔn)輸出,至于有什么不同,我目前還不清楚
System.err.println
2.2 輸入
System.in.read()
2.3 文件的操作
只需要幾個(gè)帶注釋的例子就可以了。
第一個(gè)是一個(gè)顯示文件基本信息的程序

import java.io.*;//調(diào)入和io相關(guān)的類
class fileinfo{
file://注意,main函數(shù)一定是靜態(tài)方法

  public static void main(String args[])throws IOException{
  File fileToCheck;//使用文件對(duì)象創(chuàng)建實(shí)例
  if (args.length>0){
  for (int i=0;i  fileToCheck=new File(args[i]);//為文件對(duì)象分配空間
  info(fileToCheck);//這里引用的info一定要是靜態(tài)方法成員
  }
  }
  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":""));//判斷函數(shù),如果滿足條件,輸出前者,否則輸出后者
  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.");
  }
  }
}

第二個(gè)例子是一個(gè)存儲(chǔ)電話信息的小程序,用戶輸入姓名和電話號(hào)碼,程序?qū)⑵浯嫒雙hone.numbers文件中,通過(guò)FileOutputStream來(lái)實(shí)現(xiàn)

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

2.4 流
無(wú)非是兩種
輸出流,讓我們來(lái)寫的
輸入流,給我們來(lái)讀的
java.io包中有很多種類的輸入輸出流
1.FileInputStream和FileOutputStream 節(jié)點(diǎn)流
2.BufferedInputStream和BufferedOutputStream 過(guò)濾流
3.DataInputStream和DataOutputStream 增強(qiáng)的過(guò)濾流
4.PipedInputStream和PipledOutputStream 用于線程的流


掌握了流的概念,就可以開始Sockets的學(xué)習(xí)了.關(guān)于Socket的作用,昨天我已經(jīng)講了.

現(xiàn)在,我們將創(chuàng)建一個(gè)簡(jiǎn)單的通訊程序,以獲得對(duì)Socket的實(shí)質(zhì)性的認(rèn)識(shí).該程序包括兩個(gè)部分,客戶機(jī)(RemoteFileClient)和服務(wù)器(RemoteFileServer).客戶機(jī)向服務(wù)器發(fā)出請(qǐng)求,要求讀取服務(wù)器上的文件信息.服務(wù)器將響應(yīng)請(qǐng)求,將相應(yīng)的文件信息傳給客戶機(jī),將相應(yīng)的文件信息傳給客戶機(jī).

首先我們創(chuàng)建RemoteFileClient類:
import java.io.*;//java.io 包提供對(duì)流進(jìn)行讀寫的工具,也是與 TCP 套接字通信的唯一途徑
import java.NET.*;//java.net 包提供套接字工具。

public class RemoteFileClient {
  protected String hostIp;
  protected int hostPort;
  protected BufferedReader socketReader;//負(fù)責(zé)讀數(shù)據(jù)的對(duì)象
  protected PrintWriter socketWriter;//負(fù)責(zé)寫數(shù)據(jù)的對(duì)象

file://類的構(gòu)造器有兩個(gè)參數(shù):遠(yuǎn)程主機(jī)的 ip 地址(hostIp)和端口號(hào)(hostPort)各一個(gè).構(gòu)造器將它們賦給實(shí)例變量
  public RemoteFileClient(String aHostIp, int aHostPort) {
  hostIp = aHostIp;
  hostPort = aHostPort;
  }
  public static void main(String[] args) {
  }
file://連接到遠(yuǎn)程服務(wù)器
  public void setUpConnection() {
  }
file://向遠(yuǎn)程服務(wù)器請(qǐng)求文件信息
  public String getFile(String fileNameToGet) {
  }
file://從遠(yuǎn)程服務(wù)器上斷開
  public void tearDownConnection() {
  }
}

首先來(lái)實(shí)現(xiàn)main()
public static void main(String[] args) {
  RemoteFileClient remoteFileClient = new RemoteFileClient("127.0.0.1", 3000);//為了方便調(diào)試,我們把本地服務(wù)器當(dāng)作遠(yuǎn)程服務(wù)器
  remoteFileClient.setUpConnection();//連接。不能直接使用setUpConnection,因?yàn)樗欠庆o態(tài)變量,需要?jiǎng)?chuàng)建實(shí)例后,對(duì)實(shí)例進(jìn)行引用,可以看我第一天的日記,上面寫的非常詳細(xì)
  String fileContents =
  remoteFileClient.getFile("RemoteFile.txt");//讀取

  remoteFileClient.tearDownConnection();//斷開

  System.out.println(fileContents);//輸出讀取內(nèi)容
}

步驟非常清楚.那么我們分別看連接,讀取,斷開是怎么實(shí)現(xiàn)的
1.連接
public void setUpConnection() {
  try {
  Socket client = new Socket(hostIp, hostPort);//創(chuàng)建Socket對(duì)象


  OutputStream outToServerStream=client.getOutputStream();
  InputStream  inFromServerStream=client.getInputStream();
  socketReader = new BufferedReader(new InputStreamReader(inFromServerStream));
file://把Socket的InputStream包裝進(jìn)BufferedReader 以使我們能夠讀取流的行

  socketWriter = new PrintWriter(outToServerStream);
file://把Socket的OutputStream包裝進(jìn)PrintWriter 以使我們能夠發(fā)送文件請(qǐng)求到服務(wù)器

  } catch (UnknownHostException e) {
  System.out.println("Error setting up socket connection: unknown host at " + hostIp + ":" + hostPort);
file://對(duì)Socket對(duì)象創(chuàng)建錯(cuò)誤的異常處理
  } catch (IOException e) {
  System.out.println("Error setting up socket connection: " + e);
file://對(duì)IO錯(cuò)誤的異常處理
  }
}

2.讀取
public String getFile(String fileNameToGet) {
  StringBuffer fileLines = new StringBuffer();//StringBuffer對(duì)象也是String對(duì)象,但是比它更靈活,這里是用來(lái)存放讀取內(nèi)容的

  try {
  socketWriter.println(fileNameToGet);
  socketWriter.flush();//文件存放地址輸出到socketWriter中,然后清空緩沖區(qū),讓這個(gè)地址送到服務(wù)器中去


  String line = null;
  while ((line = socketReader.readLine()) != null)
  fileLines.append(line + "n");
file://既然已經(jīng)發(fā)送到服務(wù)器去了,那我們都要等待響應(yīng),這里的程序就是等待服務(wù)器把我們所需要的文件內(nèi)容傳過(guò)來(lái)
  } catch (IOException e) {
  System.out.println("Error reading from file: " + fileNameToGet);
  }

  return fileLines.toString();//別忘了把buffer中的內(nèi)容轉(zhuǎn)成String再返回
}

3.斷開
public void tearDownConnection() {
  try {
  socketWriter.close();
  socketReader.close();
  } catch (IOException e) {
  System.out.println("Error tearing down socket connection: " + e);
  }
}

tearDownConnection() 方法只別關(guān)閉我們?cè)?Socket 的 InputStream 和 OutputStream 上創(chuàng)建的 BufferedReader 和 PrintWriter。這樣做會(huì)關(guān)閉我們從 Socket 獲取的底層流,所以我們必須捕捉可能的 IOException


好,現(xiàn)在可以總結(jié)一下客戶機(jī)程序的創(chuàng)建步驟了
1.用要連接的機(jī)器的IP端口號(hào)實(shí)例化Socket(如有問(wèn)題則拋出 Exception)。
2.獲取 Socket 上的流以進(jìn)行讀寫.
3.把流包裝進(jìn) BufferedReader/PrintWriter 的實(shí)例.
4.對(duì) Socket 進(jìn)行讀寫.具體說(shuō)來(lái),就是在Writer上傳送文件地址信息給服務(wù)器,在Reader上讀取服務(wù)器傳來(lái)的文件信息
5.關(guān)閉打開的流。

下面是RemoteFileClient 的代碼清單

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

好了,現(xiàn)在來(lái)看服務(wù)器端的程序怎么寫.
創(chuàng)建RemoteClientServer類:
import java.io.*;
import java.net.*;

public class RemoteFileServer {
  protected int listenPort = 3000;
  public static void main(String[] args) {
  }
  public void acceptConnections() {
  }
  public void handleConnection(Socket incomingConnection) {
  }
}

跟客戶機(jī)中一樣,首先導(dǎo)入 java.net 的 java.io。接著,給我們的類一個(gè)實(shí)例變量以保存端口,我們從該端口偵聽(tīng)進(jìn)入的連接。缺省情況下,端口是 3000。
acceptConnections()將允許客戶機(jī)連接到服務(wù)器
handleConnection()負(fù)責(zé)與客戶機(jī) Socket 交互以將您所請(qǐng)求的文件的內(nèi)容發(fā)送到客戶機(jī)。

首先看main()

public static void main(String[] args) {
  RemoteFileServer server = new RemoteFileServer();
  server.acceptConnections();
}
非常簡(jiǎn)單,因?yàn)橹骱瘮?shù)無(wú)非是讓服務(wù)器進(jìn)入監(jiān)聽(tīng)狀態(tài),所以直接調(diào)用acceptConnection().需要注意的是,必須先創(chuàng)建RemoteFileServer()的實(shí)例,而不是直接調(diào)用.


那么服務(wù)器是怎樣通過(guò)acceptConnection()來(lái)監(jiān)聽(tīng)客戶機(jī)的連接呢?并且如果兼聽(tīng)到了,又怎樣處理呢?我們來(lái)看
public void acceptConnections() {
  try {
  ServerSocket server = new ServerSocket(listenPort);//同客戶機(jī)的Socket對(duì)應(yīng),在服務(wù)器端,我們需要ServerSocket對(duì)象,參數(shù)是兼聽(tīng)的端口號(hào)
  Socket incomingConnection = null;//創(chuàng)建一個(gè)客戶端的Socket變量,以接收從客戶端監(jiān)聽(tīng)到的Socket
  while (true) {
  incomingConnection = server.accept();//調(diào)用該 ServerSocket 的 accept() 來(lái)告訴它開始偵聽(tīng),
  handleConnection(incomingConnection);
  }
file://不斷監(jiān)聽(tīng)直到來(lái)了一個(gè)連接請(qǐng)求,然后交由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);
  }
}

無(wú)論何時(shí)如果創(chuàng)建了一個(gè)無(wú)法綁定到指定端口(可能是因?yàn)閯e的什么控制了該端口)的 ServerSocket,Java 代碼都將拋出一個(gè)錯(cuò)誤。所以這里我們必須捕捉可能的 BindException。同時(shí),與在客戶機(jī)端上時(shí)一樣,我們必須捕捉 IOException,當(dāng)我們?cè)噲D在 ServerSocket 上接受連接時(shí),它就會(huì)被拋出??梢酝ㄟ^(guò)用毫秒數(shù)調(diào)用 setSoTimeout() 來(lái)為 accept() 調(diào)用設(shè)置超時(shí),以避免實(shí)際長(zhǎng)時(shí)間的等待。調(diào)用 setSoTimeout() 將使 accept() 經(jīng)過(guò)指定占用時(shí)間后拋出 IOException

最關(guān)鍵的處理在handleConnection()中,這時(shí)已經(jīng)連接到了客戶端的Socket,要從該Socket中讀取客戶端的請(qǐng)求并且響應(yīng)。

public void handleConnection(Socket incomingConnection) {
  try {
  OutputStream outputToSocket = incomingConnection.getOutputStream();
  InputStream inputFromSocket = incomingConnection.getInputStream();

file://首先獲取同Socket相關(guān)聯(lián)的流outputToSocket和InputStream
file://其中outputToSocket是要返回給客戶端Socket的流
file://InputStream是客戶端發(fā)來(lái)的請(qǐng)求,在這里就是文件路徑,即"RemoteFile.txt"

  BufferedReader streamReader =
  new BufferedReader(new InputStreamReader(inputFromSocket));

file://首先要將InputStream轉(zhuǎn)換到BufferedReader中

  FileReader fileReader = new FileReader(new File(streamReader.readLine()));
file://從BufferedReader中讀出文件路徑,建立新對(duì)象FileReader

  BufferedReader bufferedFileReader = new BufferedReader(fileReader);

file://再次建立BufferedReader對(duì)象,這一次它讀取得是文件里面的內(nèi)容

  PrintWriter streamWriter =
  new PrintWriter(OutputStream);

file://把Socket的outputToSocket流包裝進(jìn)PrintWriter 以使我們能夠發(fā)送文件信息到客戶端

  String line = null;
  while ((line = bufferedFileReader.readLine()) != null) {
  streamWriter.println(line);
  }
file://從bufferedFileReader中讀出文件信息,再經(jīng)由streamWriter輸出到客戶端

  fileReader.close();
  streamWriter.close();//注意Socket的兩個(gè)流關(guān)閉的順序
  streamReader.close();
file://完成之后關(guān)閉所有流

  } catch (Exception e) {
  System.out.println("Error handling a client: " + e);
  }
}


請(qǐng)注意完成所有操作之后關(guān)閉流的順序,streamWriter的關(guān)閉在streamReader的關(guān)閉之前。這不是偶然的,假如將關(guān)閉次序顛倒過(guò)來(lái),客戶端將不會(huì)獲取到任何文件信息,你可以調(diào)試一下看看.這是為什么呢?原因是如果你在關(guān)閉 streamWriter 之前關(guān)閉 streamReader,則你可以以往 streamWriter中寫任何東西,但沒(méi)有任何數(shù)據(jù)可以通過(guò)通道(通道被關(guān)閉了).但奇怪的是,我不是已經(jīng)在之前的streamWriter.println()中輸出了嗎?難道非要等到所有的流關(guān)閉之后輸出到客戶端的信息的東西才能到達(dá)?我試著將
streamWriter.close();
streamReader.close();
屏蔽掉,看是否依然能夠?qū)崿F(xiàn)正常的通信,結(jié)果發(fā)現(xiàn)不行,程序死機(jī).可能是因?yàn)橥ǖ罌](méi)有閉合導(dǎo)致的.那么至少可以說(shuō)明,只有將通道按某種順序正常關(guān)閉,才能完成通訊數(shù)據(jù)的傳輸,否則客戶端收不到信息.

最后依然是總結(jié)一下創(chuàng)建服務(wù)器端程序的步驟
1.用一個(gè)你想讓它偵聽(tīng)傳入客戶機(jī)連接的端口(比如程序中的3000)來(lái)實(shí)例化一個(gè) ServerSocket(如有問(wèn)題則拋出 Exception)。
2.循環(huán)調(diào)用ServerSocket的accept()以監(jiān)聽(tīng)連接
3.獲取客戶端的Socket流以進(jìn)行讀寫操作
4.包裝流
5.對(duì)客戶端的Socket進(jìn)行讀寫
6.關(guān)閉打開的流(切記,永遠(yuǎn)不要在關(guān)閉 Writer 之前關(guān)閉 Reader),完成通信

下面是
RemoteFileServer 的代碼清單

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

以上是“java中基礎(chǔ)知識(shí)的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

網(wǎng)站欄目:java中基礎(chǔ)知識(shí)的示例分析
網(wǎng)頁(yè)URL:http://chinadenli.net/article16/ihdggg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗(yàn)、網(wǎng)頁(yè)設(shè)計(jì)公司、App開發(fā)、電子商務(wù)、網(wǎng)站內(nèi)鏈網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁(yè)設(shè)計(jì)