android check file error“类型不匹配:推断的类型是context但不是path!“预期的”

1tu0hz3e  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(373)

我正在尝试将本地json存储引入到我正在制作的应用程序中。我以前使用过这种json存储方法,但从未遇到过这些错误; Type mismatch: inferred type is Context but Path! was expected 以及 Type mismatch: inferred type is String but LinkOption! was expected 在context和json文件上,错误如下所示:

constructor (context: Context) {
        this.context = context
        if (exists(context, JSON_FILE)) {
            deserialize()
        }
    }

以下是课程:

package ie.wit.models

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.jetbrains.anko.AnkoLogger
import java.nio.file.Files.exists
import kotlin.random.Random
import ie.wit.helpers.**/
import android.content.Context
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.jetbrains.anko.AnkoLogger
import ie.wit.helpers.*
import java.nio.file.Files.exists
import java.util.*

val JSON_FILE = "bookings.json"
val gsonBuilder = GsonBuilder().setPrettyPrinting().create()
val listType = object: TypeToken<ArrayList<ValetModel>>(){}.type

fun generateRandomId(): Long {
    return Random().nextLong()
}

class ValetJSONStore: ValetStore, AnkoLogger{
    val context: Context
    var bookings = mutableListOf<ValetModel>()

    constructor (context: Context) {
        this.context = context
        if (exists(context, JSON_FILE)) {
            deserialize()
        }
    }

    override fun findAll(): List<ValetModel> {
        return bookings
    }

    override fun create(valet: ValetModel) {
        valet.id = generateRandomId()
        bookings.add(valet)
        serialize()
    }

    override fun update(valet: ValetModel) {
        val bookingsList = findAll() as ArrayList<ValetModel>
        var foundBooking: ValetModel? = bookingsList.find{p -> p.id == valet.id}
        if(foundBooking != null){
            foundBooking.brand = valet.brand
            foundBooking.model = valet.model
            foundBooking.numberPlate = valet.numberPlate
            foundBooking.date = valet.date
        }
        serialize()
    }

    override fun delete(valet: ValetModel) {
        bookings.remove(valet)
        serialize()
    }

    private fun serialize(){
        val jsonString = gsonBuilder.toJson(bookings, listType)
        write(context, JSON_FILE, jsonString)
    }

    private fun deserialize() {
        val jsonString = read(context, JSON_FILE)
        bookings = Gson().fromJson(jsonString, listType)
    }

}
i1icjdpr

i1icjdpr1#

解释为什么会出现这样的错误:如果您检查文档 exists(..) 为了 import java.nio.file.Files.exists 它期待着 Path 而不是一个 Context :

/**
     * Tests whether a file exists.
     *
     * <p> The {@code options} parameter may be used to indicate how symbolic links
     * are handled for the case that the file is a symbolic link. By default,
     * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS
     * NOFOLLOW_LINKS} is present then symbolic links are not followed.
     *
     * <p> Note that the result of this method is immediately outdated. If this
     * method indicates the file exists then there is no guarantee that a
     * subsequence access will succeed. Care should be taken when using this
     * method in security sensitive applications.
     *
     * @param   path
     *          the path to the file to test
     * @param   options
     *          options indicating how symbolic links are handled
     * .
     * @return  {@code true} if the file exists; {@code false} if the file does
     *          not exist or its existence cannot be determined.
     *
     * @throws  SecurityException
     *          In the case of the default provider, the {@link
     *          SecurityManager#checkRead(String)} is invoked to check
     *          read access to the file.
     *
     * @see #notExists
 */
public static boolean exists(Path path, LinkOption... options) {
    try {
        if (followLinks(options)) {
            provider(path).checkAccess(path);
        } else {
            // attempt to read attributes without following links
            readAttributes(path, BasicFileAttributes.class,
                           LinkOption.NOFOLLOW_LINKS);
        }
        // file exists
        return true;
    } catch (IOException x) {
        // does not exist or unable to determine if file exists
        return false;
    }

}

可能在其他实现了相同功能的类中,可能您正试图使用 exists(..) 从其他不同的地方导入的方法 java.nio.file.Files.exists ?
要检查该文件是否存在,您有许多选项,但现在我可以列出两个选项,其中一个您已经尝试使用(exists(…)可从api 26获得):

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.io.File
import java.nio.file.Files.exists
import java.nio.file.Paths

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val JSON_FILE = "bookings.json"

        // One option to check if file exists (available from API 26)
        if (exists(Paths.get(JSON_FILE))) {
            //
        }

        // Another option to check if file exists (available from API 1)
        val file = File(JSON_FILE)
        if (file.exists()) {
            //
        }
    }
}

相关问题