提问人:Hack-R 提问时间:10/25/2015 更新时间:10/26/2015 访问量:251
使用 java.util.scanner 平台无关地从文件或 URI 的底部 n 行(尾部)进行扫描
Scan from the bottom n lines (tail) of a file or URI with java.util.scanner platform-agnostically
问:
我正在编写一个包(用于学习目的),它采用 URI 或本地文件路径并从 HTML 或文本文档中读取指定数量的行。
其中一个选项是,如果用户传递负整数作为要读取的行数,则用户应该能够阅读文档的底行。
如果我打算在 Linux/Unix 上执行此操作,我相信是这样的(我省略了代码的 URL v. 文件部分,只关注问题的核心):
Runtime r = Runtime.getRuntime()
Process p = r.exec("tail -f")
Scanner s = new Scanner(p.getInputStream())
while (s.hasNextLine()) {
String line = s.nextLine()
// Do whatever you want with the output.
}
会起作用的。但是,这不适用于 Windows。
有没有一种与平台无关的方法来做到这一点?
答:
0赞
Hack-R
10/26/2015
#1
由于没有人发布答案,因此可能没有非常直接的解决方案,但这是我最终得到的。
文件 1:MainTest.java
/**
* File: MainTest.java
*/
package mod8;
//import mod8.CaptureURI.*;
import java.io.*;
/**
* @author Jason D. Miller, Miller Intelligence LLC
*
*/
public class MainTest {
/**
* Write a program that will display lines of a text you specify.
* It should take two arguments: a file or a URL and the number of lines to display.
*
* If the number of lines given is positive, it should display the first n lines of the text.
* If it is 0, it should display all the lines of the text.
* If it is a negative number, it should display the last n lines of the text.
*
* Your program should handle errors appropriately.
*/
public MainTest() {}
/**
* @param args
*/
public static void main(String[] args) throws IOException {
//Greet and instruct user
System.out.println("********************************************");
System.out.println("* Welcome to Capture URI (aka Module 8)! *");
System.out.println("* *");
System.out.println("* Please enter a local file location *");
System.out.println("* or web URL, then press ENTER *");
System.out.println("* Next, please input the # of lines to *");
System.out.println("* capture, then press ENTER *");
System.out.println("********************************************");
//Get params
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);
System.out.println("File or web URI:");
String uri = stdin.readLine();
System.out.println("Number of lines as an integer (0 = all, negative implies tail):");
Integer lines = stdin.read();
//Pass to backend
String text = "";
text = CaptureURI.CURI(uri, lines);
//Print results
System.out.println(text);
}
}
文件 2:捕获 URI.java
package mod8;
import mod8.Tail;
import java.net.*;
import java.io.*;
import java.util.*;
public class CaptureURI {
public static boolean isLocalFile(String file) {
try {
new URL(file);
return false;
} catch (MalformedURLException e) {
return true;
}
}
public static String CURI(String uri, Integer lines) throws IOException {
String out = "";
// Get the entire file/URI
if(lines == 0){
if(isLocalFile(uri)){
try {
out = new Scanner(new File(uri)).useDelimiter("\\Z").next();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
Scanner scanner = new Scanner(new URL(uri).openStream(), "UTF-8");
out = scanner.useDelimiter("\\A").next();
scanner.close();
}
}
//Take "head" lines of file/URI
if(lines > 0){
if(isLocalFile(uri)){
try {
File file = new File(uri);
Scanner s = new Scanner(file);
for(int i = 0; i < lines; i++)
{
out += s.nextLine();
}
s.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
} else{
Scanner scanner = new Scanner(new URL(uri).openStream(), "UTF-8");
for(int i = 0; i < lines; i++)
{
out += scanner.next();
}
scanner.close();
}
}
// Take "tail" lines of file/URI
if(lines < 0){
if(isLocalFile(uri)){
try {
File file = new File(uri);
Scanner s = new Scanner(file);
out = s.toString();
//String[] ary = out.split("");
out = Tail.JavaTail(out);
s.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
} else{
Scanner scanner = new Scanner(new URL(uri).openStream(), "UTF-8");
for(int i = 0; i < lines; i++)
/*{
out += scanner.next();
}*/
out = Tail.JavaTail(out);
scanner.close();
}
}
return(out);
}
}
文件 3:Tail.java
package mod8;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* Java implementation of the Unix tail command
*
* @param args[0] File name
* @param args[1] Update time (seconds). Optional. Default value is 1 second
*
* @author Luigi Viggiano (original author) http://it.newinstance.it/2005/11/19/listening-changes-on-a-text-file-unix-tail-implementation-with-java/
* @author Alessandro Melandri (modified by)
* @author Jason Millerm hack-r.com (modified by)
* */
public class Tail {
static long sleepTime = 1000;
public static String JavaTail(String args) throws IOException {
String out = "";
BufferedReader input = new BufferedReader(new FileReader(args));
String currentLine = null;
while (true) {
if ((currentLine = input.readLine()) != null) {
out += currentLine;
continue;
}
input.close();
return(out);
/* try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
} */
//
//return(out);
}
}
}
评论