从文件输入字符串并比较输入字符串
input string from a file and compare the input string
我想从文件中输入字符串并检查每个字符串是否与给定的字符串匹配,但我做不到。在此先感谢您的帮助。
我的代码如下:
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()
函数,其中 returns 一个字符串:
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
使用 .equals 进行字符串比较。
你应该用 temp.equals()
替换 temp == "Harry" ...
我想从文件中输入字符串并检查每个字符串是否与给定的字符串匹配,但我做不到。在此先感谢您的帮助。 我的代码如下:
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()
函数,其中 returns 一个字符串:
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
使用 .equals 进行字符串比较。 你应该用 temp.equals()
替换 temp == "Harry" ...