读取Java中的文件(使用IDE) [英] Reading file in Java (IDE used)

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

问题描述

我试图编写一段Java代码来读取文件中的每一行并将其添加到Arraylist中.这是我的代码:

I was trying to write a piece of Java code to read each line from a file and add it to an Arraylist. Here is my code:

// try catch block removed for clarity.
file = new TextFileIn("names.txt");
String line = null;
while ((line = file.readLine()) != null) {
    list.add(line);
}

names.txt与我的代码位于同一软件包文件夹中.我使用的IDE是Eclipse.但是,当我运行代码时,我得到了FileNotFoundException. TextFileIn类来自 http://www.javaranch.com /doc/com/javaranch/common/TextFileIn.html

names.txt was located in the same package folder as my code. The IDE I used was Eclipse. When I run the code however I got a FileNotFoundException. The TextFileIn class comes from http://www.javaranch.com/doc/com/javaranch/common/TextFileIn.html

我如何找到要查找的文件?

How could I get the file to be found?

推荐答案

访问文件时,您依赖于当前的工作目录.工作目录取决于您启动应用程序的方式.在Eclipse中,通常是项目的根文件夹.在命令行中,它是当前打开的目录.您无法从Java代码内部进行控制,因此,对于应该作为应用程序一部分的文件,这被认为是不明智的做法.

You're relying on the current working directory when accessing the file. The working directory depends on how you started the application. In Eclipse it's usually the project root folder. In commandline it's the currently opened directory. You cannot control this from inside the Java code, so this is considered a poor practice for files which are supposed to be part of the application itself.

该文件显然与正在运行的代码位于同一软件包中,因此它已经在类路径中,然后您可以(并且应该)直接从类路径中获取该文件.

The file is apparently in the same package as the running code, thus it's already in the classpath and then you could (and should) just get it straight from the classpath.

InputStream input = getClass().getResourceAsStream("names.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
String line = null;

while ((line = reader.readLine()) != null) {
    // ...
}

如果要在static上下文中调用它,则将getClass()替换为YourClassName.class,其中YourClassName是此代码所在的类的名称.

If you're calling this in static context, then replace getClass() by YourClassName.class where YourClassName is the name of the class where this code is sitting in.

这篇关于读取Java中的文件(使用IDE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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