[英]How to read integers on file with java using Buffered Reader?
Here is the file im trying to read: 这是我正在尝试读取的文件:
P 1.0 0.0 0.0
80 10
80 30
230 37
280 30
280 10
T
t 100 -75
r 30 0 0
s 0.5 1.5 0 0
Heres part of my code: 这是我的代码的一部分:
File file = new File("coordinatess.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
glPushMatrix();
while ((st = br.readLine()) != null){
String str[] = st.split(" ");
if(str[0].equalsIgnoreCase("P")){
glColor3f(Float.parseFloat(str[1]), Float.parseFloat(str[2]), Float.parseFloat(str[3]));
}
else if(str[0].equalsIgnoreCase("T")){
br.readLine();
}
else if(str[0].equalsIgnoreCase("r")){
glRotatef(Float.parseFloat(str[1]), Float.parseFloat(str[2]), Float.parseFloat(str[3]), 0);
}
else if(str[0].equalsIgnoreCase("s")){
glScalef(Float.parseFloat(str[1]), Float.parseFloat(str[2]), Float.parseFloat(str[3]));
}
else if(str[0].equalsIgnoreCase("t")){
glTranslatef(Float.parseFloat(str[1]), Float.parseFloat(str[2]), 0);
}
}
I'm kind of having trouble reading the line without any letters. 我在读没有字母的行时有点麻烦。 Its just integers.
它只是整数。 How would I read those lines specifically, after "P"?
在“ P”之后,我将如何具体阅读这些行?
use nested level to parse values Integer.parseInt(value) with exception handling 使用嵌套级别解析具有异常处理的值Integer.parseInt(value)
String str = "T 10 5.7";
String[] strings = str.split(" ");
for (String string : strings) {
try {
System.out.println(Integer.parseInt(string));
} catch (Exception e) {
try {
System.out.println(Float.parseFloat(string));
} catch (Exception e2) {
System.out.println(string);
}
}
}
Try Santaji's way, and in try-catch block include finally
as well outside try-catch block. 尝试使用Santaji的方法,并在try-catch块中
finally
包括try-catch块之外的内容。 Your final try-catch block should look like this. 您的最终try-catch块应如下所示。 Any input stream must be closed.
任何输入流都必须关闭。
String str = "T 10 5.7";
String[] strings = str.split(" ");
for (String string : strings) {
try {
System.out.println(Integer.parseInt(string));
} catch (Exception e) {
try {
System.out.println(Float.parseFloat(string));
} catch (Exception e2) {
System.out.println(string);
}
} finally {
try {
if (file !=null) {
file.close();
}
}
}
}
But, to convert integer to string, you could possibly use other ways like : 但是,要将整数转换为字符串,您可以使用其他方式,例如:
String.valueOf(number)
(most preferred) String.valueOf(number)
(最优选)
OR 要么
Integer.toString(number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.