java 读取txt去掉重复和空行
假如现在我E盘上有个txt文件通过流把他读出来然后去掉所有相应文字的重复和空行。
假如文件是这样的:你好
再见
你好
大概就是这个意思,去掉重复和空行。感谢各位大侠
------解决方案--------------------
亚麻的。。。。我无语
import java.io.BufferedReader;
import java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Set values = new LinkedHashSet();
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream("d:/d.txt")));//文件的位置
String value = "";
while((value =bf.readLine())!=null){
value = value.trim();
if(!value.equals("")){
values.add(value);
}
}
Iterator it = values.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
} catch (
FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (
IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我同意13楼的,代码是越敲才越会,多练练,这样才能提高
------解决方案--------------------
那就这样吧。用list,这样也算是现成的吗?
Java code
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("D:\\workspace\\test\\src\\test.txt"));
List<String> lines = new ArrayList<String>();
while(true){
String line = reader.readLine();
if(line == null){
break;
}else if(line.matches("\\s*")){
continue;
}else{
if(lines.indexOf(line) == -1){
lines.add(line);
}
}
}
for(int i = 0; i < lines.size(); i++){
System.out.println(lines.get(i));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
------解决方案--------------------
String str(String source){
StringBuilder result=new StringBuilder();
boolean number=true;
for(char the:source.toCharArray()){
if(the!='\n'){
number=true;
result.appaned(the);
}else if(number){
result.appaned(the);
number=false;
}
}
}