我正在尝试编写一个mile跟踪器程序,以跟踪用户走路,跑步或游泳的距离。该程序会要求用户输入会话期间的步行距离,将其存储为双精度,从文件中读取有关先前步行距离总数的数据,将最近会话的距离与过去的总距离相加,以创建新的总距离,并将总计写入存储该文件以供将来使用的文件。 编写代码时,当我尝试将它们指向文件时,IDE会在打印编写器和扫描仪上显示错误:
Scanner reader = new Scanner(storage); //error at second Scanner
PrintWriter writer = new PrintWriter(storage); // error at second PrintWriter
错误显示为“ FileNotFoundException”
当放置在try块中时,错误消失,而是在运行时程序打印catch块错误报告:
catch(FileNotFoundException e){
System.out.println("Check that the text file is in the correct directory.");
e.printStackTrace();
}
这是我使用PrintWriter编写的第一个程序,因此,一些指针和关于我做错事情的解释将不胜感激。
这是完整的代码:
import java.io.File;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.String;
public class Main {
public static void main(String[] args) {
//gets interval data from user
System.out.println("Please type the amount of miles walked.");
Scanner input = new Scanner(System.in);
double inMiles = input.nextDouble();
//creates file and scanner that reads to file
File storage = new File ("Mile Tracker//Mile.txt");
try {
storage.createNewFile();
}
catch(IOException e ){
System.out.println("File not created.");
}
try {
Scanner reader = new Scanner(storage);
//takes data from file and sets it to a variable
double Miles = reader.nextDouble();
double TotalMiles = Miles + inMiles;
//PrintWriter reader = new PrintWriter( file );
//PrintWriter that clears the file
/*PrintWriter clearwriter = new PrintWriter(storage);
clearwriter.print("");
clearwriter.close();
*/
PrintWriter writer = new PrintWriter(storage);
writer.print(TotalMiles);
writer.close();
}
catch(FileNotFoundException e){
System.out.println("Check that the text file is in the correct directory.");
e.printStackTrace();
}
}
}
答案 0 :(得分:-1)
如果您已经有一个名为“ Mile Tracker”的目录,请检查它是否在java类的同一路径中,因为您没有显式地将路径提供给File
构造函数。如果没有“ Mile Tracker”目录,则将代码修改为:
File storage = new File ("Mile Tracker//Mile.txt");
try {
storage.getParentFile().mkdirs();
storage.createNewFile();
}
catch(Exception e ){
System.out.println("File not created.");
}
从这一点开始,应该解决FileNotFound
错误。