我有一个java问题。我想读一个txt文件,每行有一个可变数量的整数,对于每一行我需要对每一个整数进行求和!我正在使用扫描仪来读取整数,但是当一条线完成时无法工作。任何人都可以帮忙吗?Java文件读取问题
2
A
回答
2
查看用于读取文本文件的BufferedReader类和用于将每行分割为字符串的StringTokenizer类。
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
0
如果我是你,我可能会使用Apache Commons IO的FileUtils类。方法readLines(File file)
返回一个字符串列表,每行一个。然后,您可以一次处理一行。
事情是这样的:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(不幸的是下议院IO不支持泛型,所以会有分配给列出<字符串>当一个未经检查的分配警告要补救兼用@SuppressWarnings ,或者只是一个无类型的列表并将其转换为字符串。)
这也许是一种可以应用“know and use the libraries”并跳过编写一些底层样板代码的情况的示例。
0
或刮去公共要领既学到好的技术,跳过罐子:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader(new FileReader(file));
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
0
这是我将使用的解决方案。
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}
相关问题
- 1. Java文件读取问题
- 2. java文件读取问题
- 3. Java从文件读取问题
- 4. Java文件读取有什么问题?
- 5. 在java中读取文件的问题
- 6. Java - 从文件读取问题
- 7. java - 文件读取/写入问题
- 8. Android文件读取问题
- 9. 文件读取问题
- 10. 文件读取问题
- 11. 读取文件的问题
- 12. 读取UTF8文件,问题
- 13. 读取文件的问题
- 14. Python文件读取问题
- 15. Flex文件读取问题
- 16. OOP文件读取问题
- 17. 文件读取问题
- 18. 在Java NetBeans的读取文件或文件DOCX问题
- 19. Java - 读取问题txt.file
- 20. 从文件读取文本的问题
- 21. UTF8文本文件读取问题.net
- 22. Java:问题读取文本文件,然后转换
- 23. 从文件中读取文件并写入Java文件时遇到问题
- 24. Compact Framework:读取文件的问题
- 25. jQuery Ajax文件读取问题
- 26. 文件读取问题C++/C#
- 27. 问题在ASP.NET读取XML文件
- 28. 读取.xlsx文件时出现问题?
- 29. 的WebForm读取XML文件的问题
- 30. 问题读取保存的文件:Android
通过添加您的代码来完成您的问题。 – 2009-10-24 14:48:09
听起来像功课吗? – Jorn 2009-10-24 14:55:23