首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用Java读取现有的文本文件

用Java读取现有的文本文件
EN

Stack Overflow用户
提问于 2016-07-22 09:47:10
回答 4查看 2.6K关注 0票数 0

我是一名Java初学者,我正在尝试编写一个从现有文本文件中读取数据的程序。我已经尽力了,但它总是说“找不到文件!”。我已经将我的"Test.txt“复制到了包的- src和bin文件夹中。请帮我解决这个问题。我会非常感激的。这是代码-

代码语言:javascript
复制
package readingandwritingfiles;
import java.io.*;

public class ShowFile {

    public static void main(String[] args) throws Exception{
        int i;
        FileInputStream file_IN;
        try {
            file_IN = new FileInputStream(args[0]);
        }
        catch(FileNotFoundException e) {
            System.out.println("File Not Found!");
            return;
        }
        catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("Usage: ShowFile File");
            return;
        }
        do {
            i = file_IN.read();
            if(i != -1)
                System.out.print((char)i);
        } while(i != -1);
        file_IN.close();
        System.exit(0);
    }

}
EN

回答 4

Stack Overflow用户

发布于 2016-07-22 09:59:19

如果您只是放置Test.txt,那么程序将在项目的根文件夹中查找。示例:项目包-src -class -bin -Test.txt Test.txt需要与src和bin位于同一目录中,而不是位于其中

票数 0
EN

Stack Overflow用户

发布于 2016-07-22 10:06:39

将带有相对路径的字符串(或文件)传递到项目文件夹(如果您的文件位于src文件夹中,则此应为"src/Test.txt",而不是"Test.txt")。

对于读取文本文件,你应该使用FileReader和BufferedReader,BufferedReader有读取完整行的方法,你可以一直读到你发现null。

举个例子:

代码语言:javascript
复制
String path = "src/Test.txt";
try {
    FileReader fr = new FileReader(path);
    BufferedReader br = new BufferedReader(fr);
    String line = br.readLine();
    while(line != null) {
        System.out.println(line);
        line = br.readLine();
    }
    br.close();
} catch (Exception ex) {
}
票数 0
EN

Stack Overflow用户

发布于 2016-07-22 10:24:46

如果你的文件夹结构是这样的( src文件夹中的Text.txt文件)

+源+Text.txt

然后使用下面的代码

代码语言:javascript
复制
        ClassLoader classLoader = ShowFile.class.getClassLoader();
        File file = new File(classLoader.getResource("Text.txt").getFile());
        file_IN = new FileInputStream(file);

或者如果你的文件夹结构是这样的

+源+某个包+Text.txt

然后使用下面的代码

代码语言:javascript
复制
        ClassLoader classLoader = ShowFile.class.getClassLoader();
        File file = new File(classLoader.getResource("/somepackage/Text.txt").getFile());
        file_IN = new FileInputStream(file);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38516950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档