首页 > 编程语言 > 详细

JAVA入门到精通-第44讲-IO编程

时间:2018-11-30 19:33:54      阅读:151      评论:0      收藏:0      [点我收藏+]
//FileOutputStream的使用
准备把它输出到d:\\ss.txt 文件,
文件不存在直接创建;
如果存在,可能会被覆盖;
技术分享图片
//字节流
FileOutputStream fos=null;
//输出-Output-离开内存-Output/Write
//如何把string转换成bytes数组:
s.getBytes()
技术分享图片

//关闭文件流
技术分享图片

//两个字符串的换行
技术分享图片
world\r\n
\r\n就是回车换行的意思

---------------------------------------------------

java文件编程--常用io

常用io--文件字节流

1、案例[Io02.java]:读取文件(文件字节输入流使用,目的:FileInputStream)把用
FileInputStream的对象把文件读入到内存
 
1
/**
2
 * File类的基本用法
3
 * io流--文件字节流
4
 * FileInputStream类的使用
5
 */
6
import java.io.*;
7
public class Io02 {
8
    public static void main(String[] args) {
9
        //得到一个文件对象,f指向e:\ff\hsp.txt文件
10
        File f=new File("e:\\ff\\hsp.txt");
11
        FileInputStream fis=null;
12
        try {
13
            //因为File没有读写的能力,所以需要使用InputStream类
14
            fis=new FileInputStream(f);
15
            //定义一个字节数组,相当于缓存
16
            byte []bytes=new byte[1024];
17
            int n=0;//得到实际读取到的字节数
18
            //循环读取
19
            while((n=fis.read(bytes))!=-1){
20
                //把字节转成String
21
                String s=new String(bytes,0,n);
22
                System.out.println(s);
23
            }
24
        } catch (Exception e) {
25
            e.printStackTrace();
26
        }finally{
27
            //关闭文件流必需放在finally语句块中
28
            try {
29
                fis.close();
30
            } catch (Exception e) {
31
                e.printStackTrace();
32
            }
33
        }
34
    }
35
}
36

------------------------------

2、案例[Io03.java]:从键盘接收用户输入内容,并保存到文件中(文件字节输出流,目的:FileOutputStream)


x
 
1
/**
2
 * File类的基本用法
3
 * io流--文件字节流
4
 * FileOutputStream类的使用
5
 */
6
import java.io.*;
7
public class Io03 {
8
    public static void main(String[] args) {
9
        File f=new File("e:\\ff\\ss.txt");//直接覆盖写同一个文件
10
                //字节输出流
11
        FileOutputStream fos=null;
12
        if(f.exists()){
13
            System.out.println("文件已存在");
14
        }else{
15
            try {
16
                fos=new FileOutputStream(f);
17
                String s="hello,world!\r\n";
18
                String s1="中国人";
19
                fos.write(s.getBytes());
20
                fos.write(s1.getBytes());
21
            } catch (Exception e) {
22
                e.printStackTrace();
23
            }finally{
24
                try {
25
                    fos.close();
26
                } catch (Exception e2) {
27
                    e2.printStackTrace();
28
                }
29
            }
30
        }
31
    }
32
}
33
技术分享图片




































JAVA入门到精通-第44讲-IO编程

原文:https://www.cnblogs.com/xuxaut-558/p/10045771.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!