输入图像描述此处,我正在尝试使用一个文本文件来读取eclipse中的文本文件,但它找不到我放在Eclipse中的文本文件。
import java.util.Scanner;
import java.io.*;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner (System.in);
BagBase bb = new BagBase();
System.out.println("Please enter items into the bag: ");
try {
start();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void start() throws FileNotFoundException {
BagBase bb = new BagBase();
Scanner sc = new Scanner (System.in);
String wow;
File f = new File("C:/Users/sruja/workspace/Prjocet1/src/ListForBag.txt");
Scanner aa = new Scanner (f);
wow=aa.nextLine();
bb.inserItem(wow);
}
}
感谢您的帮助。我不确定为什么当我投入同一项目
"文件在eclipse"是什么意思?是在资源文件夹中吗?您的项目的结构是什么?
如果您有以下结构:
MyProject/src/main/java/analysis/ResourceReader.java
MyProject/src/main/resources/text.txt
然后,您可以访问带有以下函数的text.txt文件(将文件的名称作为参数传递给此函数):
private static Reader getReaderFromResource(String resourceName) {
URL resource = ResourceReader.class.getClassLoader().getResource(resourceName);
URL url = Objects.requireNonNull(resource);
String decodedStr = URLDecoder.decode(url.getFile(), "UTF-8");
return new FileReader(new File(decodedStr));
}
然后,您可以用执行此方法获得的实例填充一个BufferedReader构造函数(请记住有关处理异常!),并最终按行读取文件。
编辑
好吧,所以看到了您要做的事情,我会选择以下内容:
创建一个项目(最好的是一个Maven项目),因此您的结构与我已经描述的一个类似。最好在项目中的Seprate文件夹中获得资源,而不是磁盘上的某个地方。
。此代码需要一些重构,但是为了简单起见,我在这个答案中不解决它。
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
BagBase bb = new BagBase();
System.out.println("Please enter items into the bag: ");
try {
start();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void start() throws FileNotFoundException {
BagBase bb = new BagBase();
Scanner sc = new Scanner(System.in);
String wow;
List<String> dataFromFile = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(getReaderFromResource("shoppingList"))) {
String currentLine = null;
while ((currentLine = reader.readLine()) != null) {
System.out.println(currentLine); // prints content of a file, just for the record
dataFromFile.add(currentLine);
}
bb.setBag(dataFromFile);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Reader getReaderFromResource(String resourceName) throws FileNotFoundException, UnsupportedEncodingException {
URL resource = test.class.getClassLoader().getResource(resourceName);
URL url = Objects.requireNonNull(resource);
String decodedStr = URLDecoder.decode(url.getFile(), "UTF-8");
return new FileReader(new File(decodedStr));
}
}