package test0411;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class demo5 {
public static void main(String[] args) {
// 1.获取文件
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("D:\\phonenumber.txt");
fos = new FileOutputStream("D:\\phonenumber.txt",true);
// add(fos);
// delete(fis);
// change(fis);
// search(fis);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 2.查功能
// 3.增
// 4.改
// 5.删
}
private static void change(FileInputStream fis) throws IOException {
String name = "张三";
List list = new ArrayList();
Scanner sc = new Scanner(fis);
while (sc.hasNext()){
list.add(sc.next());
}
int i=0;
Object s = null;
String newnum = "9998";
while (i<list.size()){
s = list.get(i);
if (s.toString().equals(name)){
list.set(i+1,newnum);
break;
}
i+=1;
}
FileWriter fw = new FileWriter("D:\\phonenumber.txt");
while(i<list.size()){
String str = list.get(i).toString()+" "+list.get(i+1)+"\n";
System.out.println(str);
fw.write(str);
i+=2;
}
fw.flush();
fw.close();
}
private static void search(FileInputStream fis) {
String name = "张三";
List list = new ArrayList();
Scanner sc = new Scanner(fis);
while (sc.hasNext()){
list.add(sc.next());
}
int i=0;
Object s = null;
while (i<list.size()){
s = list.get(i);
if (s.toString().equals(name)){
System.out.println(list.get(i+1));
break;
}
i+=1;
}
}
private static boolean delete(FileInputStream fis) throws IOException {
String name = "李四";
boolean flat = false;
List list = new ArrayList();
Scanner sc = new Scanner(fis);
while (sc.hasNext()){
list.add(sc.next());
}
System.out.println(list);
int i=0;
Object s = null;
while (i<list.size()){
s = list.get(i);
if (s.toString().equals(name)){
list.remove(i);
list.remove(i);
break;
}
i+=1;
}
System.out.println(list);
i=0;
FileWriter fw = new FileWriter("D:\\phonenumber.txt");
while(i<list.size()){
String str = list.get(i).toString()+" "+list.get(i+1)+"\n";
System.out.println(str);
fw.write(str);
i+=2;
}
fw.flush();
fw.close();
return flat;
}
private static void add(FileOutputStream fos) throws IOException {
StringBuilder inf = new StringBuilder("");
String name = "赵六";
String num = "888888";
inf.append("\n");
inf.append(name);
inf.append(" ");
inf.append(num);
fos.write(inf.toString().getBytes());
}
}