Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中读取文件_Java_File_Bufferedreader - Fatal编程技术网

在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如果这是正确答案。