【问题标题】:How to prevent Line Reader skipping first line?如何防止 Line Reader 跳过第一行?
【发布时间】:2019-12-10 07:27:41
【问题描述】:

我正在尝试从文本文件中读取行。现在我正在计算行数,它正在跳过第一行。我认为if (line == null) break 周围有问题。我很确定我错过了什么。所以请看一下我的代码。

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (data == null)
            return
        if (requestCode==requestcode) {
            val filepath=data.data
            file = filepath.toString()
            val cursor=contentResolver.openInputStream(android.net.Uri.parse(filepath.toString()))
            lbl.text=filepath.toString()
            master_path=filepath.toString()
            noti=cursor.toString()
            val db=this.openOrCreateDatabase("database.db", Context.MODE_PRIVATE, null)
            val tableName="Master"
            db.execSQL("delete from $tableName")
            val text =  StringBuilder()
            try {
                if (resultCode == Activity.RESULT_OK) {
                    try {
                        val file=InputStreamReader(cursor)
                        val buffer=BufferedReader(file)
                        buffer.readLine()
                        var lineCount = 0
                        db.beginTransaction()

                        while(true) {
                            val line=buffer.readLine()

                            if (line == null) break //Something is wrong here I Think
                            lineCount++

                        }
                        println(lineCount.toString())
                        line = lineCount
                        db.setTransactionSuccessful()
                        db.endTransaction()
                    } catch (e: IOException) {
                        if (db.inTransaction())
                            db.endTransaction()
                        val d=Dialog(this)
                        d.setTitle(e.message.toString() + "first")
                        d.show()
                    }

                } else {
                    if (db.inTransaction())
                        db.endTransaction()
                    val d=Dialog(this)
                    d.setTitle("Only CSV files allowed")
                    d.show()
                }
            } catch (ex: Exception) {
                if (db.inTransaction())
                    db.endTransaction()

                val d=Dialog(this)
                d.setTitle(ex.message.toString() + "second")
                d.show()
            }

        }

    }

【问题讨论】:

  • 我认为这是因为您在while(true) 之前调用了一次buffer.readLine()
  • 啊,我认为你是对的。等等,让我检查一下。
  • 傻我,谢谢@Housefly

标签: android file kotlin bufferedreader


【解决方案1】:

刚刚在while(true) 之前删除了buffer.readline(),它可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2010-12-09
    • 2014-06-07
    • 2013-08-17
    相关资源
    最近更新 更多