使用DataInputStream java检查文件中的下一个数据类型



我正在尝试逐个字节地读取文件的内容。为此,我使用了DataInputStreamreadByte()方法。然而,在我这样做之后,我需要查看它读取的byte最初是char还是int,以便我可以适当地存储它。因此,基本上,在读取文件时,在将下一个字符转换为要读取的字节之前,我需要能够检查其原始数据类型。或者,在读入下一个字符之前,我可以以某种方式检查它,然后如果它是int,则使用readInt(),或者如果是char,则使用readChar().这是我当前的代码:

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 

您可以尝试类似的东西,

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

相关内容

  • 没有找到相关文章

最新更新