gpt4 book ai didi

java - 随机访问文件: Reading and Writing

转载 作者:行者123 更新时间:2023-12-01 18:39:55 24 4
gpt4 key购买 nike

我基本上想做的是首先将字符“123”写入文件test2.txt。然后我读取它,将读取的值存储在变量 z(char 数据类型)中,并将其与 (if) 部分中的“123”进行比较。但它返回 NO MATCH...即使变量 z 的值为“123”(System.out.println(z) 在屏幕上打印 123)。为什么会这样呢?我还检查了 test2.txt 文件。它包含 123,123 后面有一个小 L(由于什么原因引起?unicode 转换或其他什么??),我认为这是问题的根源。请帮忙。提前致谢。

源代码:

import java.io.*;

public class readWrite
{
public static void main(String[]args)
{
RandomAccessFile file=null;
try{
file=new RandomAccessFile("test2.txt","rw");
file.writeUTF("123");
file.seek(0);
String z=file.readUTF();
if (z=="123")
{
System.out.println("MATCH");
}
else
{
System.out.println("NO MATCH");
}
}
catch(IOException e){System.out.println(e);}
}
}

最佳答案

z 是一个字符串,应该使用 equal() 方法进行比较

尝试这样做:

    if ("123".equals(z))
{
System.out.println("MATCH");
}
else
{
System.out.println("NO MATCH");
}

此处有更多信息来比较字符串:

How do I compare strings in Java?

关于java - 随机访问文件: Reading and Writing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20374576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com