好的,所以我使用这段代码从文件中读取,但它会返回文件名。
public void read(String file){
Scanner sc = new Scanner(file);
System.out.println(sc.nextInt());
sc.close();
}
我想知道如何在阅读之前检查文件是否不存在。
答案 0 :(得分:0)
File file = new File("path of file here...");
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
while((line=in.readLine())!=null){
System.out.println(line);
}
答案 1 :(得分:0)
尝试这可能会有所帮助:
FileInputStream stream = new FileInputStream("src/transactions.txt");
fileIn = new Scanner(stream);
答案 2 :(得分:0)
扫描仪可以采用多种输入字符串/流/等。我会认真考虑尽早阅读javadocs并经常按照Sotirios Delimanolis的建议阅读。
public void read (String filename) {
try {
Scanner sc = new Scanner(new File(filename));
System.out.println(sc.nextInt());
sc.close();
} catch (FileNotFoundException) {
//handle your error here
}
}
答案 3 :(得分:0)
使用file.exists()
方法检查文件是否有效。
答案 4 :(得分:0)
要提供帮助的代码段:
BufferedReader br = new BufferedReader(new FileReader("filepath"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
line = br.readLine();
}
everything = sb.toString();
System.out.println(everything);
} finally {
br.close();
}