首页 > 解决方案 > Java,文本文件到字符串

问题描述

我正在尝试阅读某些文本文件,当我找到某个单词时,我应该做另一个标准,

在我的代码中(将遵循),我收到一个错误,“类型不匹配:无法从 int 转换为字符串”所以,Eclipse 建议的解决方案是使变量(键)整数而不是字符串这里有什么问题?

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class JNAL {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        File file = new File("C:/20180918.jrn");
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);

            System.out.println("Total file size to read (in bytes) : "
                    + fis.available());

            int content;
            String key;
            /*
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                System.out.print((char) content);
            }
            */
            while ((key = fis.read()) == "Cash") {
                // convert to char and display it
                System.out.print((String) key);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }   
    }
}

标签: java

解决方案


您在此代码中有多个问题,但只是为了解决您的问题:

(key = fis.read()) == "Cash"

“现金”是类型String。您不能将 "primitive"int与 "Object"进行比较String,因此 eclipse 建议将原语更改int为 Object type String

关键是,即使这样还不够。在比较不应该使用的对象时,请==使用equals.


推荐阅读