字节打印流(important)
@Test
//*
public void test2(){
PrintWriter pw=null;
try {
pw=new PrintWriter("PrintWriter.txt","UTF-8");
pw.write("张猛超\n");
pw.println("男");
pw.append("河南\n");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}finally {
pw.close();
}
}
字符打印流(important)
@Test
public void test1(){
PrintStream ps=null;
try {
ps=new PrintStream("PrintStream.txt","UTF-8");
ps.print("张猛超\n");
ps.print("男\n");
ps.print("21\n");
ps.append("河南");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
ps.close();
}
}
字符输出流
@Test
public void test3(){
FileWriter fw=null;
try {
fw = new FileWriter("FileWriter.txt",true);
fw.write("zhangmengchao\n");
fw.write("zhangmengchao\n");
fw.append("henan");
fw.append("张猛超\n");
fw.append("张猛超\n");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流读取和写入(important)
@Test
//*//字符流读取写入
public void test5(){
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
bufferedReader = new BufferedReader(new FileReader("A:\\U盘\\大三\\作业\\练习.txt"));
bufferedWriter =new BufferedWriter(new FileWriter("练习.txt"));
/* //第一种方式 每次读取一行
String str =null;
while ((str=bufferedReader.readLine())!=null){
System.out.println("显示读取内容"+str);
bufferedWriter.write(str);
bufferedWriter.newLine();
}*/
//第二种方式 按照字符读取
int len=0;
char [] c = new char[1024];
while ((len=bufferedReader.read(c))!=-1){
for (char c1 : c) {
System.out.println("显示读取内容"+c1);
}
bufferedWriter.write(c,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流读取和写入
@Test
//字符流读取写入
public void test4(){
Reader reader = null;
Writer writer = null;
try {
reader = new FileReader("FileWriter.txt");
writer = new FileWriter("FileWriter2.txt");
char [] c =new char[1024];
int len=0;
while ((len=reader.read(c))!=-1){
writer.write(c,0,len);
for (char c1 : c) {
System.out.print(c1);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}