文件读取 //主:Scanner,次:BufferedReader
public void read1() throws Exception {
Scanner in = new Scanner(System.in);
// 获取键盘输入
String tmp = in.nextLine();
System.out.println(tmp);
in.close();
}
public void read2() throws Exception {
BufferedReader rf = new BufferedReader(new FileReader(new File("")));
String tmp = null;
while ((tmp = rf.readLine()) != null) {
System.out.println(tmp);
}
rf.close();
}
public void read3() throws Exception {
FileInputStream rf = new FileInputStream(new File(""));
int c;
while ((c = rf.read()) != -1) {
System.out.println((char) c);
}
rf.close();
}
public void read4() throws Exception {
FileInputStream rf = new FileInputStream(new File(""));
byte[] buffer = new byte[1024];
int len;
while ((len = rf.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len));
}
rf.close();
}
public void read5() throws Exception {
FileReader rf = new FileReader(new File(""));
char[] buffer = new char[1024];
int len;
while ((len = rf.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len));
}
rf.close();
}
文件写入 //主:打印流PrintWriter
public void write1() throws Exception {
PrintWriter wf = new PrintWriter(new File(""));
wf.write("hello,world");
wf.close();
}
public void write2() throws Exception {
// FileOutputStream(File(""),true)则为后续添加,否则为覆盖内容
FileOutputStream wf = new FileOutputStream(new File(""));
int c = 65;
wf.write(c);
wf.close();
}
public void write3() throws Exception {
FileOutputStream wf = new FileOutputStream(new File(""));
byte[] buffer = new byte[1024];
System.in.read(buffer);
wf.write(buffer);
wf.close();
}
public void write4() throws Exception {
// FileWriter(File(""),true)则为后续添加,否则为覆盖内容
FileWriter wf = new FileWriter(new File(""));
wf.write("hello,world");
wf.close();
}
public void write5() throws Exception {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File("")));
BufferedWriter wf = new BufferedWriter(osw);
wf.write("hello,world");
wf.close();
}
public void fileCopy1() throws Exception {
FileInputStream rf = new FileInputStream(new File(""));
FileOutputStream wf = new FileOutputStream(new File(""));
int c;
while ((c = rf.read()) != -1) {
wf.write(c);
}
wf.close();
rf.close();
}
public void fileCopy2() throws Exception {
FileInputStream rf = new FileInputStream(new File(""));
FileOutputStream wf = new FileOutputStream(new File(""));
int len;
byte[] buffer = new byte[1024];
while ((len = rf.read(buffer)) != -1) {
wf.write(buffer, 0, len);
}
wf.close();
rf.close();
}