使用DataInputStream java检查文件中的下一个数据类型是什么?
我试图逐个字节地读入文件的内容。为此,我使用了使用DataInputStream java检查文件中的下一个数据类型是什么?,java,file,io,fileinputstream,datainputstream,Java,File,Io,Fileinputstream,Datainputstream,我试图逐个字节地读入文件的内容。为此,我使用了DataInputStream的readByte()方法。但是,在执行此操作之后,我需要查看它读入的字节最初是char还是int,以便适当地存储它。因此,基本上,在读取文件时,我需要能够在将下一个字符转换为要读取的字节之前检查下一个字符的基本数据类型。或者,我可以在读入前检查下一个字符,然后如果它是int使用readInt()或者如果它是char使用readChar()。 这是我目前的代码: public class Lexer { publ
DataInputStream
的readByte()
方法。但是,在执行此操作之后,我需要查看它读入的字节
最初是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");