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.Iterator
import java.util.LinkedHashSet
import java.util.List
import java.util.Set
public class ReadTxt {
static int NUM = 231
static String[] value = new String[NUM]
public static List<String>listFriends(File file) throws InterruptedException {
List<String>listFriends = new ArrayList<String>()
int n =0
try {
BufferedReader reader = new BufferedReader(new FileReader(file))
String line = null
while ((line = reader.readLine()) != null) {
for (int i = 0i <NUMi++) {
int beginIndex = line.indexOf(" n=")
int endIndex = line.indexOf(".com")
if(beginIndex>endIndex){
System.out.println("you are wrong!!!!!!")
n=n+1
// Thread.sleep(3000)
break
}
if(beginIndex>-1&&endIndex>-1){
value[i] = line.substring(beginIndex, endIndex)
value[i] = value[i].replaceAll("n=", "<!--")
value[i] = value[i]
.replaceAll("e=", "--><email><receiver>")
value[i] = value[i].replaceAll("\"", "")
listFriends.add(value[i] + "@qq.com</receiver></email>")
// line = line.substring(endIndex * 2 - beginIndex + 2)
break
}
else {
System.out.println("please go on!!!!!!")
// Thread.sleep(3000)
break
}
}
}
reader.close()
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
listFriends = removeDuplicateObj(listFriends)
System.out.println(n)
return listFriends
}
public static List<String>removeDuplicateObj(List<String>list) {
Set<String>someSet = new LinkedHashSet<String>(list)
Iterator<String>iterator = someSet.iterator()
List<String>tempList = new ArrayList<String>()
int i = 0
while (iterator.hasNext()) {
tempList.add(iterator.next().toString())
i++
}
return tempList
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
File file = new File(
"C:\\Documents and Settings\\Administrator\\桌面\\tttttttttttttttttt.txt")
List<String>listFriends = new ArrayList<String>()
listFriends = listFriends(file)
for (String str : listFriends) {
System.out.println(str)
}
System.out.println(listFriends.size())
}
}
如下例子代码:FileInputStream is = new FileInputStream(".")
BufferedInputStream bis = new BufferedInputStream(is)
bis.close()
从设计模式上看:
java.io.BufferedInputStream是java.io.InputStream的装饰类。
BufferedInputStream装饰一个 InputStream 使之具有缓冲功能,is要关闭只需要调用最终被装饰出的对象的 close()方法即可,因为它最终会调用真正数据源对象的 close()方法。
BufferedInputStream的close方法中对InputStream进行了关闭,下面是jdk中附带的源代码:
java.io.BufferedInputStream的api:
close
public void close()throws IOException 关闭此输入流并释放与该流关联的所有系统资源。
因此,可以只调用外层流的close方法关闭其装饰的内层流,验证例子:
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("d:\\a.txt")
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")
BufferedWriter bw = new BufferedWriter(osw)
bw.write("java IO close test")
bw.close()
}
验证ok