2017-09-23 247 views
-3

我想从文件中输入字符串并检查每个字符串是否与给定的字符串匹配,但我无法完成。预先感谢您的帮助。 我的代码如下:从文件输入字符串并比较输入字符串

import java.util.*; 
import java.io.*; 
import org.apache.commons.io.*; 
import java.nio.charset.*; 

public class XYZ 
{ 
    String s[] = {"Harry","Potter","Pirates","Of","The","Carribean"}; 

    XYZ() 
    { 
     save(); 
     String []copyString = load(); 
     for(int i=0; i<6; i++) 
     { 
      System.out.print("String " + i + ": " + copyString[i]); 
     } 
    } 

这是我save()函数的字符串保存到一个文件:

public void save() 
{ 
    DataOutputStream output = null; 
    try 
    { 
     output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("the-file-name.txt"))); 
     for(int i=0; i<6; i++) 
     { 
      output.writeUTF(s[i]); 
     } 
     output.close(); 
    } 
    catch(IOException e){}  

} 

这是我load()函数返回一个字符串:

public String[] load() 
    { 
     final Charset UTF_8 = Charset.forName("UTF-8");  
     String temp; 
     String copyFromFile[] = new String[6]; 

     DataInputStream input = null; 
     try 
     { 
      input = new DataInputStream(new BufferedInputStream(new FileInputStream("the-file-name.txt"))); 
      for(int i=0; i<6; i++) 
      { 

       temp = input.readUTF(); 
       if(temp == "Harry" || temp == "Potter" || temp == "Pirates" || temp == "Of" || temp == "The" || temp == "Carribean") 
       { 
        copyFromFile[i] = temp; 
       } 
       else 
       { 
        System.out.println("Not matched"); 
       } 
      } 
      input.close(); 
     }catch (IOException e){} 
     return copyFromFile; 
    } 

最后,我的main()功能:

public static void main(String[]arg) 
{ 
    XYZ xyz = new XYZ(); 

} 

}

输出:

Not matched 
Not matched 
Not matched 
Not matched 
Not matched 
Not matched 

回答

0

的字符串比较使用.equals。 你应该用temp.equals()代替temp ==“Harry”...