系统找不到Kotlin中指定的文件 [英] The system cannot find the file specified in Kotlin

查看:121
本文介绍了系统找不到Kotlin中指定的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从同一包中读取文件,因此当我运行代码时,它会给我错误

I try to read from file in same package so when i run code it give me error

var buffer: BufferedReader? = null

val result = try {

    buffer = BufferedReader(FileReader("file.txt"))
    val chars = CharArray(30)
    buffer.read(chars, 0, 40)
    0
} catch (e: IndexOutOfBoundsException) {
    println(" Exception handle")
    1
} catch(e: FileNotFoundException) {
    println(e.message)
    2
} finally {
    buffer?.close()
    println("closed")
}

println(result)

输出:

file.txt(系统找不到指定的文件)

file.txt (The system cannot find the file specified)

关闭

2

当我指定完整路径FileNoFoundException时不抛出原因吗?.

when i specify full path FileNoFoundException not throw why ?.

var buffer: BufferedReader? = null

val result = try {
    buffer = BufferedReader(FileReader("C:\\Users\\Mahmood Ali\\IdeaProjects\\Kotlin wih hadi\\src\\tidbits\\file.txt"))
    val chars = CharArray(30)
    buffer.read(chars, 0, 40)
    0
} catch (e: IndexOutOfBoundsException) {
    println("Exception handle")
    1
} catch(e: FileNotFoundException) {
    println(e.message)
    2
} finally {
    buffer?.close()
    println("closed")
}

println(result)

输出:

异常句柄

关闭

1

推荐答案

如果传递不带路径的文件名,则JVM将在当前工作目录中查找该文件,而不是进行呼叫的类的package文件夹.因此,要使用相对路径,必须首先找出程序的工作目录,如果从intelliJ中运行它,则该目录通常应该是项目的根文件夹.

If you pass a filename without a path, the JVM is going to look for that file in the current working directory, not the package folder of the class you're making the call from. So, to use relative paths, you have to first find out the working directory of your program, which should usually be the root folder of the project if you're running it from intelliJ.

这篇关于系统找不到Kotlin中指定的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆