我想写一个简单的程序,读取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);
做我想做的事情最优雅的方式是什么?
答案 0 :(得分:3)
以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));
}
}
}
此代码只读取前五行,然后以相反的顺序输出它们。
答案 1 :(得分:1)
读入数组并在其上调用反向函数或递减循环。