在java中读取文件
好的,我用这段代码读取文件,但它返回文件名在java中读取文件,java,file,bufferedreader,Java,File,Bufferedreader,好的,我用这段代码读取文件,但它返回文件名 public void read(String file){ Scanner sc = new Scanner(file); System.out.println(sc.nextInt()); sc.close(); } 我想知道如何在读取文件之前检查文件是否不存在。试试看这可能会有帮助: File file = new File("path of file here..."); BufferedReader in = ne
public void read(String file){
Scanner sc = new Scanner(file);
System.out.println(sc.nextInt());
sc.close();
}
我想知道如何在读取文件之前检查文件是否不存在。试试看这可能会有帮助:
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);
}
FileInputStream stream = new FileInputStream("src/transactions.txt");
fileIn = new Scanner(stream);
扫描仪可以采用多种输入字符串/流等。我会认真考虑JavaDoc的早期和经常如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
}
}
使用file.exists()
方法检查文件是否有效。代码片段帮助:
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();
}
在使用类之前,请先阅读它们的javadoc。使用带有
FileNotFoundException
的try/catch块。如果要读取文件内容,请使用newscanner(新文件(“pathToFile”)
。如果使用新扫描仪(“某些字符串”)
它将只读取传递字符串的内容。@angeldarkland如果这是正确答案。