gpt4 book ai didi

java - 如何用Java搜索文件并返回值?

转载 作者:行者123 更新时间:2023-12-01 15:32:06 25 4
gpt4 key购买 nike

我需要一些有关以下代码的帮助。
我想做的是从文件中的行中读取数据。我想到的方法是使用 while 循环来迭代各行,尝试找到特定的“x_y_z”并使用 indexOf() 方法查看它是否存在。所以基本上我想运行循环直到得到一个不是 -1 的值,然后中断循环并返回该值。我在返回值时遇到问题...我似乎无法将其从循环中取出。有人可以帮我吗?

import java.io.InputStreamReader;
import org.bukkit.entity.Player;

/**
*
* @author Tim
*/
public class ReadIn {

public static int read(String path, int x, int y, int z, Player player) {
try {
FileInputStream fstream = new FileInputStream(path);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;

//Read File Line By Line
int index = -1;
while ((strLine = br.readLine()) != null && index == -1) {
index = strLine.indexOf(x + "_" + y + "_" + z);
if (index != -1) {
int value = index;
break;
}
}

//Close the input stream
in.close();

} catch (Exception exception) {//Catch exception if any
exception.printStackTrace();
}
}
}

非常感谢,
蒂姆

最佳答案

您的代码无法编译,该方法不返回任何值!改为这样做:

    public static int read(String path, int x, int y, int z, Player player) {
int value = -1;
try {
FileInputStream fstream = new FileInputStream(path);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = "";
//Read File Line By Line
int index = -1;
while ((strLine = br.readLine()) != null) {
index = strLine.indexOf(x + "_" + y + "_" + z);
if (index != -1) {
value = index;
break;
}
}
//Close the input stream
in.close();
} catch (Exception exception) {//Catch exception if any
exception.printStackTrace();
}
return value;
}

值现在将包含正确的索引,否则为 -1。

关于java - 如何用Java搜索文件并返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9447204/

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