java如何截取竖行
在Java中截取竖行(即按列截取字符串或文本)通常涉及处理多行字符串或文本文件中的特定列。以下是几种常见方法:
使用String的substring方法
对于固定宽度的文本,可以使用substring按列截取。假设每行有固定宽度,要截取第start到end列的字符:

String line = "example line";
int start = 2; // 起始列(从0开始)
int end = 5; // 结束列
String column = line.substring(start, end);
处理多行文本
对于多行文本(如文件内容),可以逐行处理并截取指定列:

List<String> lines = Files.readAllLines(Paths.get("file.txt"));
int columnStart = 3;
int columnEnd = 7;
List<String> result = new ArrayList<>();
for (String line : lines) {
if (line.length() >= columnEnd) {
result.add(line.substring(columnStart, columnEnd));
}
}
使用正则表达式
若列内容有特定模式(如由空格或制表符分隔),可以用正则表达式提取:
String line = "a b c d";
String[] columns = line.split("\\s+"); // 按空白字符分割
String targetColumn = columns[1]; // 获取第2列(索引从0开始)
使用第三方库(如Apache Commons CSV)
对于CSV等结构化文本,使用库可以简化列提取:
CSVParser parser = CSVParser.parse(file, StandardCharsets.UTF_8, CSVFormat.DEFAULT);
for (CSVRecord record : parser) {
String columnValue = record.get(1); // 获取第2列
}
注意事项
- 列索引通常从0开始。
- 处理文件时需考虑编码和异常处理。
- 对于非固定宽度文本,需先标准化或使用分隔符。






