java IO之FileInputStream和FileOutputStream

本文提供了一个使用Java进行文件读写的示例程序。通过两个单元测试方法,分别演示了如何从文件中读取内容并打印到控制台,以及如何将文件内容复制到另一个文件中。这些示例有助于理解Java中文件输入输出流的基本用法。
 1 package com.io.test;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 
 8 import org.junit.Test;
 9 
10 public class TestFileStream {
11 
12     @Test
13     public void testFileInputStream() {
14         try {
15             FileInputStream is = new FileInputStream("E:/1.txt");
16             int b = 0;
17             int num = 0;
18             while ((b = is.read()) != -1) {
19                 System.out.print((char) b);
20                 num++;
21             }
22             is.close();
23             System.out.println();
24             System.out.println("共输出" + num + "个字符");
25         } catch (FileNotFoundException e) {
26             e.printStackTrace();
27         } catch (IOException e) {
28             e.printStackTrace();
29         }
30     }
31     
32     
33     @Test
34     public void testFileOutputStream() {
35         try {
36             FileInputStream is = new FileInputStream("E:/1.txt");
37             FileOutputStream os = new FileOutputStream("E:/2.txt");
38             int b = 0;
39             while ((b = is.read()) != -1) {
40                 os.write(b);
41             }
42             is.close();
43             os.close();
44             
45         } catch (FileNotFoundException e) {
46             e.printStackTrace();
47         } catch (IOException e) {
48             e.printStackTrace();
49         }
50 
51     }
52 }

转载于:https://www.cnblogs.com/cjunj/archive/2012/11/05/2755727.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值