简体   繁体   English

无法从文本文件读取

[英]Unable to read from a text file

I am trying to read from a text file. 我正在尝试从文本文件读取。 I have the file created, it only needs to have one record, but it could have more. 我已经创建了文件,它只需要一个记录,但是可以有更多记录。 I keep getting errors. 我不断出错。 I am a Geography student, not an IT guy, I am hoping to figure out the next step once I get this. 我是地理专业的学生,​​而不是IT专家,我希望一旦掌握这一点,便可以找出下一步。 Here is my example, that doesn't work: 这是我的示例,不起作用:

import java.io.*;
import java.util.*;
import java.lang.*;
public class Driver
{
       public static void main(String[] args) throws IOException
       {
            File data;
            String fileName = null; // User input file name

            Scanner input;
            input = new Scanner(System.in); 

            System.out.println("Enter file name (ie: text.txt): ");
            data = new File(input.next());

            Scanner read;
            read = new Scanner(data);

            fileName = read.nextLine();

            System.out.println(fileName);
        }
 }

I believe an error that you are having is not referencing the correct place when trying to access the file. 我认为您尝试访问文件时遇到的错误未引用正确的位置。 If you just type in example.txt, the java compiler has no idea where to find this file. 如果仅输入example.txt,则Java编译器不知道在哪里可以找到此文件。 Try this: 尝试这个:

  • Right click under the package 右键单击包装下的
  • Create new folder, and call it 'texts' 创建新文件夹,并将其称为“文本”
  • Open file explorer 打开文件浏览器
  • Paste all your .txt files into this new folder 'texts' 将所有.txt文件粘贴到此新文件夹“文本”中
  • Replace fileName = read.nextLine(); 替换fileName = read.nextLine(); with fileName = "texts/" + read.nextLine(); 使用fileName =“ texts /” + read.nextLine();

After this you should be good to go! 在此之后,您应该一切顺利!

You have two options. 您有两个选择。

  • Put text.txt file in same folder where your class files are. text.txt文件放在类文件所在的文件夹中。

  • Get full path of the file from user like C:\\text.txt . 从用户那里获取文件的完整路径,例如C:\\text.txt

It'll run. 它会运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM