能用记事本编辑的都是普通文本文件 不一定是1.txt 如1.java
一.FileReader
package com.io;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/*
FileReader :
文件字符输入流,只能读取普通文本
读取文本内容时,比较方便,快捷
*/
public class FileReaderTest {
public static void main(String[] args) {
FileReader reader =null;
try {
//创建文件字符输入流
reader = new FileReader("temp.txt");
char[] chars = new char[4];//一次读取4个字符
int readCount = 0;
while((readCount = reader.read(chars))!=-1){
System.out.print(new String(chars,0,readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
二.FileWriter
package com.io;
import java.io.FileWriter;
import java.io.IOException;
/*
FileWriterTest:
文件字符输出流。写
只能输出普通文本
*/
public class FileWriterTest {
public static void main(String[] args) {
FileWriter out =null;
try {
//创建文件字符输出流对象
//out = new FileWriter("file");
//以追加的形式在文件末写入
out = new FileWriter("file",true);
out.write("我长得是真的帅");
char[] chars ={'帅','是','真','的','帅'};
out.write(chars ,0,5);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
三.文件拷贝
package com.io;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*
使用FileReader和FileWriter进行拷贝,只能拷贝普通文本文件
*/
public class copy02 {
public static void main(String[] args) {
FileReader in = null;
FileWriter out =null;
try {
in =new FileReader("file");
out = new FileWriter("file2");
int readCount=0;
char[] chars = new char[1024*502];//1MB
while((readCount=in.read(chars))!=-1){
out.write(chars,0,readCount);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}