我最近开始编程,无法让程序找到文件,然后从中读取输入。说该文件不存在。这是我的代码。
import java.util.*;
import java.io.*;
public class assignment3 {
public static void main(String args[]) throws IOException {
PrintWriter pw = new PrintWriter("C:\\file\\Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n" +
"---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.next();
File f = new File(filename);
System.out.println(f);
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
在线扫描仪inputfile = new Scanner(f);.出现错误。此外,当提示在程序中输入文件名时,我输入“C:/Games.txt”.....但是当我得到要打印的文件名时,文件名被注册为C:\ Games.txt。 ...为什么正斜线会变成反斜杠。感谢您抽出宝贵时间帮助我。
答案 0 :(得分:0)
为什么正斜线会变成反斜杠?
因为您在Windows上,并且目录由\
接下来,您似乎没有使用PrintWriter
撰写文章。如果您想检查存在的文件,请致电File#exists()
。
File f = new File(filename);
if (f.exists()) {
System.out.println(f);
Scanner inputFile = new Scanner(f);
while (inputFile.hasNextLine()) {
System.out.println(inputFile.nextLine());
}
} else {
System.out.println(f.getPath() + " does not exist");
}
答案 1 :(得分:0)
确保名为“file”的文件夹存在(用于创建文件)。如果它不存在,它可能会抛出该错误。阅读时你需要拥有适当的权利。
答案 2 :(得分:0)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Answer {
public static void main(String args[]) throws IOException, FileNotFoundException {
// Have to throw a FileNotFoundException just in case an error occurs the compiler needs to know how to process the error.
PrintWriter pw = new PrintWriter("C:/file/Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out
.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n"
+ "---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.nextLine(); //Input for strings
System.out.println(filename);
File f = new File("C:/file/"+filename+".txt"); //Must have a location for your files
f.createNewFile(); //The file's pathname is the only thing that you can supply when you instantiate the object
//you actually have to invoke the createNewFile method upon the object.
if(f.exists()) { //Don't be afraid to check your code this is a must for every programmer.
System.out.println("Good! The File Exists");
}
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
创建文件时,如果不这样做,则始终必须抛出FileNotFoundException
,如果发生错误,编译器将不知道该怎么做。使用/指定文件目录时。
\通常用作转义序列,当你输入这个\ \你基本上告诉它自己逃避时,这个代码在其他情况下很有用,但不是这个。
您无法通过启动对象来创建新文件,而该对象始终需要在对象上调用createNewFile方法,以便您可以创建新文件。这是因为没有构造函数自动调用类中的createNewFile方法。您可能想知道参数中的单词是什么,它们只是用于命名文件目录。如果您想查看创建文件,我找到了一个有用的链接。只需在构造函数选项卡下查看。 API Files Class
确定!要始终检查您的代码,无论您是多么优秀的程序员都无所谓。您总是必须检查错误,如果您进行游戏,并且不知道错误在数百万行代码中的位置。你将会有一段时间。
最后,我不确定你在if语句之后想要做什么,但是你会在if语句之后收到错误,所以如果你想问我如何帮助你只需输入我的评论交。