我需要打开文件,但它在主函数中给出了一个错误 我试图让用户但文件名如果不正确,程序将给出错误消息并终止程序 这是我的计划。
//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;
}
}
}
答案 0 :(得分:0)
我假设您正在尝试读取名为stocks.txt的文件并逐行获取其内容,您可以通过多种方式执行此操作
使用Files API
import java.nio.file.Files; import java.nio.file.Paths;
列出行= Files.readAllLines(Paths.get(uri), Charset.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 (..) {}
你可以使用其中一种方法来实现它,使用Files API更容易。