[英]can not open the file in java program
我需要打開文件,但它在主函數中給我一個錯誤我試圖讓用戶但文件名如果不正確程序將給出錯誤消息並終止程序這是我的程序。
//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.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 是更簡單的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.