无法在java程序中打开该文件
我需要打开文件,但它在主函数中给了我一个错误 我试图让用户,但文件名,如果它是不正确的程序将给出一个错误消息,并终止程序 这是我的节目无法在java程序中打开该文件,java,Java,我需要打开文件,但它在主函数中给了我一个错误 我试图让用户,但文件名,如果它是不正确的程序将给出一个错误消息,并终止程序 这是我的节目 //import java.io.File; //import java.io.PrintWriter; import java.util.Scanner; import java.io.*; // file input/output import java.io.IOException; public class Stock{ String name
//import java.io.File;
//import java.io.PrintWriter;
import java.util.Scanner;
import java.io.*; // file input/output
import java.io.IOException;
public class Stock{
String name;
String symbol;
double Price;
//Random randomNumbers = new Random();//Generate random numbers
Stock(){ // no-argument constructor
name="";
symbol="";
Price=0.0;
}
Stock(String n,String s,double p){ //constructor with argument
name=n;
symbol=s;
Price=p;
}
public void setname(String name){//mutators to set the value of name
this.name=name;
}
public void setsymbol(String symbol){//mutators to set the value of symbol
this.symbol=symbol;
}
public void setnextPrice(double price){
this.Price = price;
}
public String getname(){//accessor to get the name
return name;
}
public String getsymbol(){ //accessor to get the symbol
return symbol;
}
public double getPrice(){//accessor to get currentPrice
return Price;
}
public void openfile()throws IOException{
String f="";
System.out.print("Please enter the file name: "+f);
if (f.equals("stocks.txt")){
Scanner x;
x= new Scanner(new File("stocks.txt"));
//PrintWriter outputFile = new PrintWriter("output.txt");
String name = x.nextLine();
System.out.println(name);
}
else{
System.out.println("File Not Found");
return;
}
}
}
我假设您正在尝试读取一个名为stocks.txt的文件,并逐行获取其内容,您可以通过多种方式执行此操作 使用文件API 导入java.nio.file.Files; 导入java.nio.file.path 列表行=文件.readAllLines(路径.get(uri)), defaultCharset()) 迭代此列表并获取内容 使用扫描仪
File file = new File("stock.txt");
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
使用
File file = new File("stocks.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
}
catch (..) {}
您可以使用其中一种方法来实现它,使用文件API是更简单的方法。这是主函数//导入java.io.*//文件输入/输出导入java.util.Scanner//导入java.io.IOException;公共类股票列表{Scanner input=null;public static void main(字符串[]arg){Stock Stock=new Stock();Stock stock2=new Stock(名称、符号、pric);Stock.openfile();}}请编辑您的问题并正确设置代码格式。看起来您在主要方法中混淆了
stock
和stock2
。所有与解决此问题相关的信息都应包含在问题中(而不是在评论部分)。请编辑您的问题,并毫不犹豫地修剪与此问题无关的代码位。感谢您的帮助。如果我想获得最高价格和最低价格,并从文件中计算平均值,该怎么办?而不是一行一行地