您的位置:首页 > 其它

从磁盘读取文本文档,用逗号隔开,但是要求双引号内的逗号不能隔开,放到ArrayList中输出

2012-11-19 16:56 309 查看
程序如下:

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

public class Demo{

public static List<String> splitString(String str){

List<String> list=new ArrayList<String>();

int i=1;

String[] strs =str.split("\"");

for(int m=0;m<strs.length;m++){

if(strs[m].equals("")){

continue;

}

if(m==i){ //字符串一定出现在奇数个上

String st="\""+strs[m]+"\"";

list.add(st);

i+=2;

}else{

String stss=strs[m];

String[] ss=stss.split(",");

for(int n=0;n<ss.length;n++){

if(!ss
.equals("")){

list.add(ss
);

}

}

}

}

return list;

}

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

String Dir="D:/input.txt";

File sampleDir=new File(Dir);

FileReader samReader = new FileReader(sampleDir);

BufferedReader samBR = new BufferedReader(samReader);

String word=new String();

StringBuffer words =new StringBuffer();

ArrayList arr =new ArrayList();

while((word = samBR.readLine())!=null){

words.append(word);

}

String wordss=words.substring(0);

List<String> list=splitString(wordss);

for(int i=0;i<list.size();i++){

System.out.println(list.get(i));

}

}

}

运行结果:

a

b

"c,d"

e

fg

h
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐