Java文件的输入输出方式包括按字节流输入输出和按字符字符输入输出。
字节流
字节流的输入包括:Inputstream,FileInputStream,BufferedInputStream,DataInputStream;输出包括:Outputstream,FileOutputStream,BufferedOutputStream,DataOutputStream。
示例1:
public class FileIOTest {
@Test
public void test() throws IOException {
InputStream in = null;
OutputStream out= null;
try {
in=new FileInputStream("C:read.txt");
out=new FileOutputStream("C:write.txt");
byte []by=new byte[1024];
int ch;
while((ch=in.read(by))!=-1){
out.write(by);
out.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
out.close();
}
}
}
示例2:
public class FileIOTest {
@Test
public void test() throws IOException {
BufferedInputStream in = null;
BufferedOutputStream out= null;
try {
in=new BufferedInputStream(new FileInputStream("C:read.txt"));
out=new BufferedOutputStream(new FileOutputStream("C:write.txt"));
byte []by=new byte[1024];
int ch;
while((ch=in.read(by))!=-1){
out.write(by);
out.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
out.close();
}
}
}
BufferedInputStream和BufferedOutputStream都是将内容先放在缓冲区,然后进行处理,效率更高。
字符
字符的输入包括:Reader,FileReader,BufferedReader;输出包括:Writer,FileWriter,BufferedWriter。
示例1:
public class FileIOTest {
@Test
public void test() throws IOException {
Reader in = null;
Writer out= null;
try {
in=new FileReader("C:read.txt");
out=new FileWriter("C:write.txt");
int line;
while((line=in.read())!=-1){
out.write((char)line);
System.out.println((char)line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
out.close();
}
}
}
示例2:
public class FileIOTest {
@Test
public void test() throws IOException {
BufferedReader in = null;
BufferedWriter out= null;
try {
in=new BufferedReader(new FileReader("C:read.txt"));
out=new BufferedWriter(new FileWriter("C:write.txt"));
String line;
while((line=in.readLine())!=null){
out.write(line);
System.out.println(line);
}
//out.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
out.close();
}
}
}