Java基础(3):文件输入输出

        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();
}
}

}




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值