FileNotFound错误,但我的txt文件与java文件位于同一位置
所以我有一个程序,它应该读取一个关于物品清单的txt文件,问题是当我运行它时,我发现这个文件inventory.txt没有找到。我把它都放在同一个文件夹中,java文件、类文件和txt文件,但仍然没有发生任何事情。代码如下:FileNotFound错误,但我的txt文件与java文件位于同一位置,java,io,bufferedreader,filenotfoundexception,Java,Io,Bufferedreader,Filenotfoundexception,所以我有一个程序,它应该读取一个关于物品清单的txt文件,问题是当我运行它时,我发现这个文件inventory.txt没有找到。我把它都放在同一个文件夹中,java文件、类文件和txt文件,但仍然没有发生任何事情。代码如下: import java.util.StringTokenizer; import java.io.*; import java.text.DecimalFormat; class InventoryItem { private String name; priv
import java.util.StringTokenizer;
import java.io.*;
import java.text.DecimalFormat;
class InventoryItem {
private String name;
private int units; // number of available units of this item
private float price; // price per unit of this item
private DecimalFormat fmt;
public InventoryItem (String itemName, int numUnits, float cost) {
name = itemName;
units = numUnits;
price = cost;
fmt = new DecimalFormat ("0.##");
}
public String toString() {
return name + ":\t" + units + " at " + price + " = " +
fmt.format ((units * price));
}
}
public class Inventory{
// Reads data about a store inventory from an input file,
// creating an array of InventoryItem objects, then prints them.
public static void main (String[] args) {
final int MAX = 100;
InventoryItem[] items = new InventoryItem[MAX];
StringTokenizer tokenizer;
String line, name, file="inventory.txt";
int units, count = 0;
float price;
try{
FileReader fr = new FileReader (file);
BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();
while (line != null) {
tokenizer = new StringTokenizer (line);
name = tokenizer.nextToken();
try {
units = Integer.parseInt (tokenizer.nextToken());
price = Float.parseFloat (tokenizer.nextToken());
items[count++] = new InventoryItem (name, units, price);
}
catch (NumberFormatException exception) {
System.out.println ("Error in input. Line ignored:");
System.out.println (line);
}
line = inFile.readLine();
}
inFile.close();
for (int scan = 0; scan < count; scan++)
System.out.println (items[scan]);
}
catch (FileNotFoundException exception) {
System.out.println ("The file " + file + " was not found.");
}
catch (IOException exception) {
System.out.println (exception);
}
}
}
编辑:我的坏我没有指定目录,所以我的文件在我的下载文件中,所以路径是cd\users\person\downloads。我这里有Inventory.java、Inventory.class和Inventory.txt文件尝试创建一个新文件夹,我们现在称之为text。然后,您的代码将如下所示:
//your code here
String line, name, file="texts\\inventory.txt";
//more code
希望这有帮助 file=inventory.txt;try file=src/inventory.txt;它必须位于当前工作目录中,该文件名才能工作。与源目录无关,在部署时,源目录在运行时不存在。也许你应该把它作为一种资源来使用?
//your code here
String line, name, file="texts\\inventory.txt";
//more code