gpt4 book ai didi

java - 读取 URL 的前 5 行,然后以相反的顺序打印

转载 作者:行者123 更新时间:2023-11-29 03:57:32 24 4
gpt4 key购买 nike

我想写一个简单的程序,读取 URL 的前五行,然后以相反的顺序打印出来,所以它是第 5 行、第 4 行、第 3 行、第 2 行、第 1 行。

这是我到目前为止所得到的:

public static void main(String[] arg) throws Exception {

BufferedReader keyboard;
String inputLine;

keyboard = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Please enter the name of a company (without spaces): ");
System.out.flush(); /* Make sure the line is printed immediately. */
inputLine = keyboard.readLine();

URL u = new URL("http://www." + inputLine + ".com/");
InputStream ins = u.openStream();

InputStreamReader isr = new InputStreamReader(ins);
BufferedReader readURL = new BufferedReader(isr);

做我想做的事情最优雅的方法是什么?

最佳答案

Reading Directly from a URL作为初始示例,因为它已经是一段优雅的代码,可以满足您的需求。例如……

import java.net.*;
import java.io.*;
import java.util.*;

public class DataURL {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

int i=5; /* number lines */
List<String> lines = new ArrayList<String>();
while (i>0 && (inputLine = in.readLine()) != null) {
lines.add(inputLine);
i--;
}
in.close();

for (i=lines.size()-1; i >= 0; i--) {
System.out.println("Line " + i + ": " + lines.get(i));
}
}
}

这段代码只是简单地读取前五行,然后倒序输出。

关于java - 读取 URL 的前 5 行,然后以相反的顺序打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5473275/

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