gpt4 book ai didi

java - 如何从 ArrayList 中提取特定数字?

转载 作者:行者123 更新时间:2023-11-29 04:13:25 25 4
gpt4 key购买 nike

我写了一个程序,可以从 http://worldtimeapi.org/api/ip.txt 中获取文本数据, 并提取 X,其中 X 是“unixtime”旁边的值。这是我到目前为止得到的结果。

public class GetDataService implements DataService{
@Override
public ArrayList<String> getData() {
ArrayList<String> lines = new ArrayList<>();
try {
URL url = new URL("http://worldtimeapi.org/api/ip.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
String a = line;
lines.add(a);
}
bufferedReader.close();

} catch (IOException ex) {
throw new RuntimeException("Can not making the request to the URL.");
}
return lines;
}

public interface DataService {
ArrayList<String> getData() throws IOException;
}

public class UnixTimeExtractor {
private GetDataService getDataService;

public String unixTimeExtractor() {
ArrayList<String> lines = getDataService.getData();
//how to extract the value next to "unixtime"

我不知道如何提取“unixtime”旁边的值。以及如何测试 GetDataService 类的网络错误。

最佳答案

I don't know how to extract value next to "unixtime".

要从列表中提取值,您可以遍历列表,根据需要对每个值进行一些检查,并在找到匹配项时返回值,例如:

for (String line : lines) {
if (line.startsWith("unixtime: ")) {
return line;
}
}

要提取字符串中“unixtime:”之后的值,您可以使用多种策略:

  • line.substring("unixtime: ".length())
  • line.replaceAll("^unixtime: ", "")
  • line.split(": ")[1]
  • ...

顺便说一句,你真的需要行列表吗?如果不是,那么在从 URL 读取输入流时执行此检查可以节省内存并减少输入处理,找到所需内容后立即停止阅读。

And how can I test NetWork Error for GetDataService Class.

为了测试网络错误是否被正确处理,您需要使可能引发网络错误的代码部分可注入(inject)。然后在您的测试用例中,您可以注入(inject)将抛出异常的替换代码,并验证程序是否正确处理异常。

一种技术是“提取和扩展”。即,提取对专用方法的 url.openStream() 调用:

InputStream getInputStream(URL url) throws IOException {
return url.openStream();
}

并将您的代码 url.openStream() 替换为对 getInputStream(url) 的调用。然后在你的测试方法中,你可以通过抛出异常来覆盖这个方法,并验证会发生什么。在 AssertJ 中使用流畅的断言:

  @Test
public void test_unixtime() {
UnixTimeExtractor extractor = new UnixTimeExtractor() {
@Override
InputStream getInputStream(URL url) throws IOException {
throw new IOException();
}
};
assertThatThrownBy(extractor::unixtime)
.isInstanceOf(RuntimeException.class)
.hasMessage("Error while reading from stream");
}

您可以对输入流进行类似的读取。

关于java - 如何从 ArrayList 中提取特定数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53755627/

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