在空白处拆分文本文件

时间:2015-05-03 07:39:04

标签: java file split java.util.scanner delimiter

Scanner sc = new Scanner("textfile.txt");
List<String> tokens = new ArrayList<String>();

for (int i =0 ; sc.hasNextLine(); i++)
{
    String temp = sc.nextLine();
    tokens.add(temp);
}

我的文本文件看起来像

A
B
C
*empty line* 
D
E
F
*empty line* 

依旧......

我遇到的麻烦是我试图将每个部分存储到一个数组(包括空行),但我不知道如何分割这些部分。按部分我的意思是A B C 空行,是一个部分。

3 个答案:

答案 0 :(得分:1)

如果你只是将它分成新的行而不是空格,这就是你使用protected void gridPhones_RowDeleting(object sender, ASPxDataDeletingEventArgs e) {...} protected void gridPhones_RowInserting(object sender, ASPxDataInsertingEventArgs e) {...} protected void gridPhones_RowUpdating(object sender, ASPxDataUpdatingEventArgs e) {...} protected void gridPhones_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e) { var grid = sender as ASPxGridView; if (!grid.IsEditing) return; if (e.Column.FieldName == "Type") { var combo = e.Editor as ASPxComboBox; combo.Font.Name = "Tahoma"; if (combo.Items.Count == 0) { var types = LookupManager.Instance.GetAllByEnum<PhoneType>(); combo.DataSource = types.OrderByDescending(p => p.Value); combo.TextField = "Title"; combo.ValueField = "Value"; combo.DataBind(); } } else if (e.Column.FieldName == "CountryCode") { var txt = e.Editor as ASPxTextBox; txt.NullText = @"0098"; } else if (e.Column.FieldName == "CityCode") { var txt = e.Editor as ASPxTextBox; txt.NullText = @"021"; } else if (e.Column.FieldName == "Phone") { var txt = e.Editor as ASPxTextBox; txt.NullText = @"81022000"; //This is my conditional nulltext if (e.KeyValue == null) return; var val = grid.GetRowValuesByKeyValue(e.KeyValue, "Type").ToString(); if (!string.IsNullOrEmpty(val) && val.ToInt32(0) == (int)(PhoneType.Mobile)) txt.NullText = @"09126994040"; //This is my conditional nulltext } } hasNextLine()时的情况,你可以试试这个。

nexLine()

答案 1 :(得分:0)

在您从文件中读取时,不是将每行添加到列表中,而是 附加到字符串构建器或临时字符串。当您检测到新行时,将其附加到临时字符串或字符串构建器后,将目前为止所有内容添加到列表中。重复,直到你有行。

答案 2 :(得分:0)

请参阅最初的示例:最初:

package com.raj;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Echo {

public static void main(String[] args) throws Exception {

Scanner sc 
= new Scanner(new File("textfile.txt"));
List<StringBuilder> tokens 
= new ArrayList<StringBuilder>();
StringBuilder builder 
= new StringBuilder();

boolean saveFlag = true;


while (sc.hasNextLine()) {
String temp = sc.nextLine();

if (temp.isEmpty()) {
tokens.add(builder);
builder = new StringBuilder();
saveFlag = false;
continue;
}

builder.append(temp + "\n");
saveFlag = true;
}
sc.close();

if (saveFlag) tokens.add(builder);

for (StringBuilder sb : tokens) {
System.out.println(sb);
}

}
}