FileReader
從文件中讀取消息
package Inputoutputcopy;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/*
* 文件字符輸入流
*
*/
public class fileread {
public static void main(String[] args) {
//創建源
File file = new File("dest.txt");
//選擇流
Reader read = null;
try {
read= new FileReader(file);
char[] ch = new char[1024];
int len =-1;//接受長度
while((len=read.read(ch))!=-1) {
//字符數組到字符串
String str = new String(ch,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(read!=null) {
try {
read.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
FileWriter
往文件中寫入消息
package Inputoutputcopy;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class filewritw {
public static void main(String[] args) {
//創建源
File file = new File("dest.txt");
//選擇流
Writer writer = null;
try {
//操作
writer = new FileWriter(file);
//方法一
String str = "josephus is so handsome";
char[] ch= str.toCharArray();//字符串--》字符數粗
writer.write(ch,0,ch.length);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(writer!=null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
其中註釋方法一的地方還可以改爲
直接
writer(String)
//方法二
String str = "josephus is so handsome yes";
writer.write(str,0,str.length());
writer.flush();//刷新流 刷新之後再close
最後一個方法三
append
append的優點是可以直接通過writer對象調用,而且還可以連續調用
如:
writer.append("josephus is ").append("very ").append("handsome!");
writer.flush();//刷新不能少