2015-12-03 30 views
0

我想逐個字節地逐個讀取文件內容。爲此,我正在使用DataInputStreamreadByte()方法。但是,我這樣做後,我需要看看它所讀取的byte最初是char還是int,所以我可以適當地存儲它。所以基本上,在讀取文件時,我需要能夠檢查下一個字符的基本數據類型,然後再將其轉換爲字節進行讀取。 Alternativly,我可以以某種方式檢查下一個字符之前,我讀它,那麼如果它是一個int使用readInt(),或者如果它是一個char使用readChar(). 這裏是我當前的代碼:使用DataInputStream java檢查文件中的下一個數據類型是什麼?

public class Lexer { 
    public static void main(String a[]) { 
     try { 
      File file = new File("placeholder.txt"); 
      DataInputStream is = new DataInputStream(new FileInputStream(file)); 
      char c; 
      int i; 
      byte b; 

      while((b = is.readByte()) != -1) { 
       //here, I would like to now store my byte to c, or i based on what type it 
       // originally was. 

      } 
     } catch(FileNotFoundException e) { 
      System.out.println("Fatal Error: Could not find program source code file"); 
     } catch (IOException e) { 
      System.out.println("Fatal Error: Could not i/o with source code file"); 
     } 


    } 
    //} 
} 

文件內容:

javarocks1234! //while reading, I need to know if the next byte I read in was a char or an int in this file 

回答

0

你可以嘗試像,

String readtxt = "9999"; // reading string from file 
java.util.regex.Pattern numberPatter = java.util.regex.Pattern.compile(".*[^0-9].*"); 

if(numberPatter .matcher(readtxt).matches()) 
    System.out.println("it's numeric"); 
else 
    System.out.println("It's not a numeric"); 
相關問題