简体   繁体   English

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

[英]Check what the next datatype is in a file using DataInputStream java?

I am trying to read in the contents of a file byte by byte individually. 我试图逐字节逐个读取文件的内容。 TO do this, I'm using the DataInputStream 's readByte() method. 为此,我使用了DataInputStreamreadByte()方法。 However, after I do this, I need to see if the byte it read in was originally a char or an int so I can store it appropriately. 但是,执行完此操作后,我需要查看它读取的byte原来是char还是int以便可以适当地存储它。 So basically, when reading a file I need to be able to check what the next character's primitive datatype is before converting it to a byte to read. 因此,基本上,在读取文件时,我需要能够在将下一个字符的原始数据类型转换为要读取的字节之前对其进行检查。 Alternativly, I could somehow check the next character before I read it in, then if it's an int use readInt() or if its a char use readChar(). 或者,在读入下一个字符之前,我可以通过某种方式检查它,如果它是int使用readInt() ,如果它是char使用readChar(). Here is my current code: 这是我当前的代码:

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


    }   
    //}
}

File Contents: 文件内容:

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

you can try something like, 您可以尝试类似

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM