使用Java中的Scanner类读取.txt文件 [英] Reading a .txt file using Scanner class in Java

查看:400
本文介绍了使用Java中的Scanner类读取.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个逐行读取文本文件的Java程序,每个文本文件都带有一个数字,每个数字都将其引发到数组中,然后尝试使用插入排序对数组进行排序。

我收到以下错误消息:


  java.io.FileNotFoundException:10_Random(系统找不到指定的文件)
在java.io.FileInputStream.open(Native Method)$ < init>(Unknown Source)$ b $ java.util.Scanner。< init>(Unknown Source)
在insertionSort.main(insertionSort.java: 14)


我有我的.txt文件的副本srcbin和主项目文件夹,但仍无法找到该文件。顺便说一句,我正在使用Eclipse。

  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);

尝试{

扫描仪sc =新扫描仪(文件);

while(sc.hasNextLine()){
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch(FileNotFoundException e){
e.printStackTrace();




$ div class =h2_lin>解决方案


$ b

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆