1. 程式人生 > >c詞法分析程式(java實現)原始碼1

c詞法分析程式(java實現)原始碼1

package wordanalyse;
 
import java.io.*;
public class InputFile {
 private String path="";
 public InputFile(){
  
 }
 /**
  * @author 楊武兵
  *function:從鍵盤獲得原始檔的絕絕對路徑,改變屬性path的值。
  *@return void 
  */
 public void  getPathFromKeys(){
  int count;
  byte b[]=new byte[256];
  BufferedInputStream in=new BufferedInputStream(System.in);  /*獲得系統標準輸入——鍵盤,作為緩衝輸入。*/
  File file=null;
  try{
   if(in.markSupported())
   {
    System.out.println("說明:這是一個簡單的詞法分析程式");
    System.out.println("它不能對包含檔案進行操作。");
    System.out.println("請輸入原始檔的絕對路徑");
    System.out.println("長度不能超過256個位元組!");
    System.out.println("輸入完後請按enter回車結束!");
    do{
     in.mark(256);
     count=in.read(b);
     this.path=new String(b,0,count-2);
     if(!path.substring(path.length()-2).equals(".c"))
     {
      System.out.println("溫情提示:請最好輸入c原始檔!");
      
     }
     file=new File(this.path);
     if(!file.isFile())
      System.out.println("你輸入的檔案不存在,請重新輸入!");
    }while(!file.isFile());
   }
   else
   {
    System.out.println("不支援mark()方法!");
   }
   in.close();
  } 
  catch(Exception e)
  {
   System.out.println("發生I/O錯誤!");
  }
 }
 public void setPath(String path)
 {
  this.path=path;
 }
 public String getPath()
 {
  return this.path;
 }
 /**
  * @author 楊武兵
  * @return 返回從原始檔裡讀出來的字串。
  * @fuction 從絕對路徑為this.path的檔案裡
  */
 public String getContentFromFile()
 {
  int count;
  byte b[]=new byte[10*1024];  //可以輸入的檔案檔案大小是10*1024個位元組,可以修改。
  String content="";
  FileInputStream fipt=null;
  DataInputStream din=null;
  try{
   fipt=new FileInputStream(this.getPath());
   din=new DataInputStream(fipt);
   count=din.read(b);
   content=new String(b,0,count);
   return content;
  }
  catch(Exception e)
  {
   System.out.println("發生I/O錯誤!"+e.toString());
   return content;
  }
 }
 /**
  * @author 楊武兵
  * @param source 源字串,即從原始檔裡面讀出來的字串。
  * @return 返回字元陣列,有兩個字串,一個是取得的當前行的字元,另一個是除了當前行以外的字串。
  */
 public String[] getOneLineString(String source)
 {
  if(source!=null)
  { 
   byte []b;
   String []returnString=new String[2];
   b=source.getBytes();
   for(int i=0;i<b.length;i++)
   if(b[i]=='\n')
   {
    returnString[0]=new String(b,0,i-1);
    returnString[1]=new String(b,i+1,b.length-i-1);
    return returnString;
   }
   returnString[0]=source; /*如果當前字串沒有換行符,則將作為一行。*/
   return returnString;
  }
  else
  {
    return null;
  }
 }
}