1.获取键盘输入
public class MyConsole {
private static Scanner sc;
public static String inputFromConsole(){
String input = null;
BufferedReader br1;
try {
br1 = new BufferedReader(new InputStreamReader(System.in,"UTF-8"));
input=br1.readLine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return input;
}
}
2.从文件中读取
File f = new File(tableAddress);
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br1.close();
3.从文件中删除
//方法:生成一个临时文件,读出,把需要的读入,删除的不读,最后,把原来文件删掉,把临时文件rename成原文件的名字
File f = new File(tableAddress);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
File tempFile = new File(tableAddress + ".tmp");
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String str = null;
str = br.readLine();
while (str != null) {
String split[] = str.split(" ");
if (!split[0].equals(index)) {
pw.println(str);
pw.flush();
}
split = null;
str = br.readLine();
}
pw.close();
br.close();
fr.close();
// FileWriter fw = new FileWriter(f, false);
// BufferedWriter bw = new BufferedWriter(fw);
// bw.write(newFile);
// bw.close();
// fw.close();
f.delete();
tempFile.renameTo(f);
}
4.从文件中修改
//如果不包含要修改的信息,直接添加到newFile,包含则修改后添加,最后把newFile读回,注意,append要设为false
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String str = null;
str = br.readLine();
int count = 0;
String newFile = "";
while (str != null) {
if (!str.contains("admin")) {
if (count == 0)
newFile += str;
else
newFile += "\r\n" + str;
} else
newFile += "admin" + " " + password;
count++;
str = br.readLine();
}
br.close();
fr.close();
FileWriter fw = new FileWriter(f, false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(newFile);
bw.close();
fw.close();