我想在基于序列的列表中将文件拆分为Header和详细信息。
想要使用标题和细节拆分文本文件我试过这样的事情,但没有帮助。
我想调用迭代器的前一次迭代,但我不能......
文件:
H>>>>>>
L>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>> ...
我想:
列出1,H,L,L,L
列出2,H,L,L
列出3与H,L
代码尝试:
List<String> poString = new ArrayList<String>();
if(poString !=null && poString.size() > 0)
{
ListIterator<String> iter = poString.listIterator();
while(iter.hasNext())
{
String tempHead = iter.next();
List<String> detailLst = new ArrayList<String>();
if(tempHead.startsWith("H"))
{
while(iter.hasNext())
{
String detailt = iter.next();
if(!detailt.startsWith("H"))
detailLst.add(detailt);
else
{
iter.previousIndex();
}
}
}
}
答案 0 :(得分:0)
试试这个(未经测试):
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
List<StringBuilder> myList = new List<StringBuilder>();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line[0] == 'H')
{
myList.add(sb);
sb = new StringBuilder();
}
sb.append(line[0]);
line = br.readLine();
}
} finally {
br.close();
}
答案 1 :(得分:0)
你可以使用它..
public static void main(String a[]) throws Exception
{
ArrayList<String> headers=new ArrayList();
ArrayList<String> lines=new ArrayList();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
File f= new File("inputfile.txt");
Scanner scanner = new Scanner(f);
try {
while (scanner.hasNextLine()){
String ss=scanner.nextLine();
String key= String.valueOf(ss.charAt(0));
if ( map.containsKey(key))
{
ArrayList<String> temp=(ArrayList) map.get(key);
temp.add(ss);
map.put(key, temp);
}
else
{
ArrayList<String> temp= new ArrayList();
temp.add(ss);
map.put(key, temp);
}
}
}
catch(Exception e)
{
throw e;
}
}
答案 2 :(得分:0)
据我了解,最终文件中有多少H..lines
,您希望有多少List<String>
。
如果您不知道确切的数字(在您的示例中,它是3),那么您有一个列表列表(List<List<String>>
)。
//read the file, omitted
List<List<String>> myList = new ArrayList<<List<String>>();
List<String> lines = null;
boolean createList = false;
while (line != null) {
if (line.startsWith("H")){
myList.add(lines);
lines = new ArrayList<String>();
}
//if the 1st line of your file not starting with 'H', NPE, you have to handle it
lines.add(line);
line=readnextlineSomeHow(); //read next line
}
上述代码可能不会开箱即用,但它会为您提供想法。
答案 3 :(得分:0)
尝试这个,我已经尝试了一点,我的工作
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
ArrayList<ArrayList<String>> result = new ArrayList<> ();
int numlines =0;
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line.startsWith("H"))
{
result.add(new ArrayList<String>());
result.get(numlines).add("H");
line = br.readLine();
while(line != null && !line.startsWith("H")){
if(line.startsWith("L")) result.get(numlines).add("L");
line = br.readLine();
}
++numlines;
}
else line = br.readLine();
}
} finally {
br.close();
}