我行的LACS的一个文本文件分割线读取一个字段和单行格式如下:由标签
a | b | c(may contain url) | d(may contain url)
我想提取的最后一个字段的完整文本即从线路d
。
一旦我使用BufferedReader读取了该行,我该怎么做。
我行的LACS的一个文本文件分割线读取一个字段和单行格式如下:由标签
a | b | c(may contain url) | d(may contain url)
我想提取的最后一个字段的完整文本即从线路d
。
一旦我使用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.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);
lins.substring(line.lastIndexOf(X));
line.lastIndexOf(x)将返回最后找到的x符号的索引(在这种情况下,x是一个制表符(\ t)),您可以从该索引获取行的子字符串。 如果您的最后一个字段也包含该符号,则应使用正则表达式。
您驾驶室商店,你从文件中读取到一个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);