我正在尝试用java编写一个小程序,它将根据球体的半径计算球体的表面积和体积。这些半径来自包含单列数字的 .txt 文件。
我尝试过搜索一下: Reading numbers in java
代码示例对我来说看起来有点复杂,因为我在阅读 Java 代码方面还不太舒服,也没有经验。我也尝试过阅读这篇文章:
Opening and reading numbers from a text file
我对“try”关键字感到困惑,除此之外,它的用途是什么?
第二个示例显示 File("file.txt");
我是否输入文本文件的路径?
如果有人可以向我指出一个可以帮助初学者完成这些事情的教程,我非常想知道。
这是迄今为止我的代码:
import java.io.*;
//该类读取包含单列数字的文本文件 (.txt)
公共(public)类ReadFile {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName = "/home/jacob/Java Exercises/Radii.txt";
Scanner sc = new Scanner(fileName);
}
}
最诚挚的问候,
雅各布·科尔斯特鲁普
最佳答案
这是一个简单的小片段:
Scanner in = null;
try {
in = new Scanner(new File("C:\\Users\\Me\\Desktop\\rrr.txt"));
while(in.hasNextLine()) {
int radius = Integer.parseInt(in.nextLine());
System.out.println(radius);
// . . .
}
} catch(IOException ex) {
System.out.println("Error reading file!");
} finally {
if(in != null) {
in.close();
}
}
try-catch
block 是 Java 中用来处理异常的东西。您可以在这里阅读有关它们的所有信息以及它们为何有用:http://docs.oracle.com/javase/tutorial/essential/exceptions/
当然,如果您使用的是Java 7或更高版本,则可以使用称为try-with-resources
的东西来简化前面的代码。这是另一种类型的 try
block ,只不过这会自动为您关闭任何“可自动关闭”流,从而删除代码中丑陋的 finally
部分:
try (Scanner in = new Scanner(new File("C:\\Users\\Me\\Desktop\\rrr.txt"))) {
while(in.hasNextLine()) {
int radius = Integer.parseInt(in.nextLine());
System.out.println(radius);
// . . .
}
} catch(IOException ex) {
System.out.println("Error reading file!");
}
您可以在此处阅读有关 try-with-resources
的更多信息:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
rrr.txt
文件每行应该只有一个数字,如下所示
10 20 30
关于java - 使用scanner/reader/bufferedreader读取文本文件以读取.txt文件中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13564375/