簡體   English   中英

Java,文本文件到字符串

[英]Java, Text File to String

我正在嘗試讀取某些文本文件,並且當我找到某些單詞時,我應該執行另一個條件,

在我的代碼中(將接下去),我得到一個錯誤,“ 類型不匹配:無法從int轉換為String ”因此,Eclipse建議的解決方案是使變量(鍵)為整數而不是String此處的錯誤之處是什么?

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();
            }
        }   
    }
}

您在此代碼中有多個問題,但是只是要解決您的問題:

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

“現金”的類型為String 您不能將“ primitive” int與“ Object” String ,因此,eclipse建議將原始int更改為Object type String

關鍵是,即使這還不夠。 比較對象時,不應使用==而應使用equals

嘗試這個

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class JavaTextFileToString {


        public static void main(String[] args) throws Exception {
            File file = new File("C:/20180918.jrn");

            BufferedReader br=new BufferedReader(new FileReader(file));
            String line=null;
            while((line=br.readLine())!=null){
                if(line.equals("Cash")) {
                    System.out.println(line);
                }

            }

            br.close();
        }
    }

嘗試這個:

BufferedReader bf = new BufferedReader(new InputStreamReader(fis));

while ((key = bf.readLine()).equals("Cash")) 

==運算符比較對象的引用,因此您應該使用equals()方法比較String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM