使用 Java 中的 Scanner 类读取 .txt 文件 [英] Reading a .txt file using Scanner class in Java
本文介绍了使用 Java 中的 Scanner 类读取 .txt 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个 Java 程序,它逐行读取文本文件,每个文件都有一个数字,将每个数字放入一个数组中,然后尝试使用插入排序对数组进行排序.我需要帮助让程序读取文本文件.
我收到以下错误消息:
<块引用>java.io.FileNotFoundException: 10_Random (系统找不到指定的文件)在 java.io.FileInputStream.open(本机方法)在 java.io.FileInputStream.(来源不明)在 java.util.Scanner.(来源不明)在 insertSort.main(insertionSort.java:14)
我的src"bin"和主项目文件夹中有 .txt 文件的副本,但它仍然找不到该文件.顺便说一下,我正在使用 Eclipse.
import java.io.File;导入 java.io.FileNotFoundException;导入 java.util.Scanner;公共类插入排序{公共静态无效主(字符串 [] args){File file = new File("10_Random");尝试 {扫描仪 sc = 新扫描仪(文件);而 (sc.hasNextLine()) {int i = sc.nextInt();System.out.println(i);}sc.close();}抓住(FileNotFoundException e){e.printStackTrace();}}}
解决方案
你必须把文件扩展名放在这里
File file = new File("10_Random.txt");
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source) at java.util.Scanner.<init>(Unknown Source) at insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
解决方案
You have to put file extension here
File file = new File("10_Random.txt");
这篇关于使用 Java 中的 Scanner 类读取 .txt 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文