2012-11-26 18 views
1

我正试图在java中编写一个小程序,它将计算表面积和一个球体的体积,基于半径领域。这些半径来自带有一列数字的.txt文件。使用扫描仪/读取器/缓冲读取器读取文本文件以读取.txt文件中的数字

我试着搜索了一下这个: Reading numbers in java

的示例代码看起来有点复杂,我因为我还没有舒适,经历了阅读Java代码。我也试着阅读这一个:

Opening and reading numbers from a text file

我弄糊涂了“尝试”关键字的,除其他事项外,是什么在那里?

其中第二个示例说File("file.txt");我是否将路径放入我的文本文件?

如果任何人都可以给我一个教程,让初学者通过这些事情,我非常想知道。

这是到目前为止我的代码:

import java.io.*; 

//这个类读取包含数字的一列

公共类的ReadFile {一个文本文件(.txt)

/** 
* @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); 

} 

}

此致敬礼,

雅各Collstrup

回答

0

这里有一个小的,简单的片断:

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块是在Java中用于处理异常东西。你可以阅读所有关于他们,为什么他们在这里是有用:http://docs.oracle.com/javase/tutorial/essential/exceptions/


当然,如果你使用的Java 以上,以前的代码可以使用一种叫try-with-resources被简化。这是另一种类型的try块,除了这个会自动关闭任何“autocloseable”流为你,删除代码的那个丑陋的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
+0

我想你的建议的第二部分,我曾试图以确保我的理解是在做什么了。它工作得很好!谢谢。现在我只需要弄清楚如何从另一个程序调用它来使用那里的数据。 –

0

-try/catch,最后是处理Exceptions或(因为延伸Throwable Class),在执行一些工作时出现。

如:文件I/O,网络运营等

Scanner in = null; 

try { 

    in = new Scanner(new File("C:\\Users\\Me\\Desktop\\rrr.txt")); 

    while(in.hasNextLine()) { 

    int radius = Integer.parseInt(in.nextLine()); // If this is  
               // not an integer 
               // NumberFormatException is thrown. 
     System.out.println(radius); 


    } 

} catch(IOException ex) { 

    System.out.println("Error reading file!"); 

} catch(NumberFormatException ex){ 

    System.out.println("Its not an integer"); 
} 
finally { 
    if(in != null) { 
     in.close(); 
    } 
}