流按操作数据分为两种:字节流和字符流
字节流分为两个基类:InputStream和OutputStream。
字符流分为两个基类:Reader和Writer。
练习向文件里写入“abcd”字符串
package it.learnJava;
import java.io.FileWriter;
import java.io.IOException;
public class IOWriterDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//创建一个FileWriter对象,并明确被操作的文件
FileWriter fw = new FileWriter("C:/xc.txt");
fw.write("abcde");
//close和flush的区别:flush刷新后,并没有关闭流
// fw.flush();
fw.close();
}
}
IO异常处理方式
package it.learnJava;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FileWriter fw = null;
try {
fw = new FileWriter("C:/xc.txt");
fw.write("avdf");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(fw != null)
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
copy文件的两种方法
package it.learnJava;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFile {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
copy_2();
}
public static void copy_2() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("C:/xc.txt");
fw = new FileWriter("D:/scy.txt");
char []buf = new char[1024];
int len = 0;
while((len = fr.read(buf))!=-1)
{
fw.write(buf, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
} finally {
if(fr!=null)
{
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
}
}
if(fw!=null)
{
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
}
}
}
}
public static void copy_1() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("C:/xc.txt");
fw = new FileWriter("D:/xc.txt");
int ch = 0;
while((ch=fr.read())!=-1)
{
fw.write(ch);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("2");
} finally {
try {
if(fr!=null)
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("3");
}
try {
if(fr!=null)
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("4");
}
}
}
}