无法从文本文件中读取
问题描述:
我正在尝试从文本文件中读取数据。我创建了文件,它只需要有一条记录,但它可能有更多。我不断收到错误。我是一名地理学学生,而不是IT人员,我希望一旦得到这一点,就能找出下一步。这里是我的榜样,不工作:无法从文本文件中读取
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);
}
}
答
我相信你有试图访问文件时不引用正确位置的误差。如果你只是输入example.txt,java编译器不知道在哪里找到这个文件。 试试这个:
- 右键单击包
- 下创建新的文件夹,并将其命名为“文本”
- 打开文件浏览器
- 您的所有.txt文件粘贴到这个新文件夹“文本”
- 替换fileName = read.nextLine(); with fileName =“texts /”+ read.nextLine();
之后,你应该很好去!
答
你有两个选择。
把
text.txt
文件放在你的类文件所在的同一文件夹中。获取用户的文件的完整路径,如
C:\text.txt
。
它会运行。
你会得到什么错误? [我没有](http://melpon.org/wandbox/permlink/OWVpKLf6enn6osN5)。 – MikeCAT
[读取Java中的纯文本文件]可能的重复(http://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java) –
'我不断收到错误'什么错误?请发布您遇到的错误。谢谢。 – Pang