JAVA中的FileReader
- FileReader:
文件字符输入流,只能读取普通文本文件
读取文本内容时,比较方便快捷。
public class FileReaderTest01 {
public static void main(String[] args) {
FileReader fr = null;
try {
fr = new FileReader("src\\io\\copiedfile.txt");
char[] chars = new char[4];
int readCount ;
while ((readCount = fr.read(chars)) != -1){
System.out.println(new String(chars,0,readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
JAVA中的FileWriter
public class FileWriterTest01 {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter("src/io/fileWriterFile.txt");
char[] chars = {'我','有','一','只','小','乌','龟'};
fw.write(chars);
fw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
使用FileReader和FileWriter完成文件的复制:
public class FileWriterTest02 {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("src\\io\\FileWriterTest01.java");
fw = new FileWriter("src/io/fileWriterCopy.txt");
char[] chars = new char[4];
int readerCount;
while ((readerCount = fr.read(chars)) != -1){
fw.write(chars,0,readerCount);
}
fw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}