【发布时间】:2011-12-21 02:34:03
【问题描述】:
我有一个 lacs of line 的文本文件,单行格式如下:
a | b | c(may contain url) | d(may contain url)
我想从行中提取最后一个字段中的完整文本,即d。
使用 BufferedReader 读取该行后,我该怎么做。
【问题讨论】:
标签: java string bufferedreader
我有一个 lacs of line 的文本文件,单行格式如下:
a | b | c(may contain url) | d(may contain url)
我想从行中提取最后一个字段中的完整文本,即d。
使用 BufferedReader 读取该行后,我该怎么做。
【问题讨论】:
标签: java string bufferedreader
一种可能的方式如下:
package eu.webfarmr.stackoverflow;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* The goal of this class is to read lines from a text file which contain
* vertical bars and extract the fields separated by these tabs
*
* @author djob
*
*/
public class FileLACSReader {
private final static String SEPARATOR = "\\|";
/**
*
* @param args
*/
public static void main(String args[]) throws Exception{
List<String> lines = readContents("etc/sampleInput.txt");
for (String input : lines) {
String[] splitContent = input.split(SEPARATOR);
for (String field : splitContent) {
System.out.println(field);
}
}
}
public static List<String> readContents(String file)
throws FileNotFoundException {
List<String> textLines = new ArrayList<String>();
FileInputStream stream = new FileInputStream(new File(file));
Scanner scanner = new Scanner(stream);
try {
while (scanner.hasNextLine()) {
textLines.add(scanner.nextLine());
}
} finally {
scanner.close();
}
return textLines;
}
}
我希望这会有所帮助。
【讨论】:
您可以将从文件中读取的文本存储到 String 中,而您可以这样做:
String str = "a | b | c(may contain url) | d(may contain url)";
int x = str.lastIndexOf("|");
String str1 = str.substring(x+2);
System.out.println(str1);
【讨论】:
lins.substring(line.lastIndexOf(x));
line.lastIndexOf(x) 将返回最后找到的 x 符号的索引(在这种情况下 x 是制表符 (\t)),您可以从该索引中获取行的子字符串。
如果您的最后一个字段也包含该符号,则应使用正则表达式。
【讨论】:
你可以使用 String.split 方法:
String line = "a | b | c(may contain url) | d(may contain url)";
String[] parts = line.split("\\|");
String lastPart = parts[parts.length - 1];
System.out.println(lastPart);
【讨论】: