Java文件和文件流
知识:在程序中对file的操作(读写),需要先将file转换成流,然后从流中读写data
java I/O
Java IO中用于读写文件的四个抽象类:Reader,Writer,InputStream,OutputStream。
根据流所处理的数据类型分为两类:
(1)字节流:用于处理字节数据。(InputStream,OutputStream),子类是(FileInputStream,FileOutputStream)
(2)字符流:用于处理字符数据,Unicode字符数据。(Reader,Writer),子类是(FileReader,FileWriter)
Java中I/O流的操作,主要在Android是保存持久化数据
1.字符流(Reader、Writer) — 读取(写入)相关的字符(String),不需要缓冲区。
2.字节流(InputStream、OutputStream) — 读取(写入)相关的字节,需要先将数据读入(写入)缓冲区,然后再将缓冲区读入(写入)流中。
public static void main(String[] args) {
MyClass fileDemo = new MyClass();
File file = new File("C:\\Users\\**\\Desktop\\test.txt");
// fileDemo.FileReader();//先写再读
fileDemo.FileWriter(file);
fileDemo.FileReader(file);
}
private void FileReader(File file) {
// File file = new File("C:\\Users\\ya.zhang.REALLYTEK\\Desktop\\test.txt");
try {
char[] arr = new char[1024];
FileReader fr = new FileReader(file);
int length = fr.read(arr);
for(int i = 0; i < length ; i++){
System.out.println(arr[i]);
}
fr.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
private void FileWriter(File file){
// File file = new File("C:\\Users\\**\\Desktop\\test.txt");
if(file.exists()){
//
}else{
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileWriter fw = new FileWriter(file,true);
String str = "abcd";
fw.write(str,0, str.length());
fw.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
借鉴:https://www.jianshu.com/p/ac276d6ac64b