• 技术文章 >java >java基础

    java字符流和字节流替换方法

    小妮浅浅小妮浅浅2021-01-04 16:03:06原创2716

    在学习IO流的种类后,我们明确不同流在图片或者文字的处理上都有对应的使用。那么当一种流不适用于当前的使用时,就需要把字符流和字节流进行转化,这就涉及到了轮换流的使用。下面我们先就轮换流的用法进行学习,然后进一步讲解字符流和字节流的替换方法。

    1.转换流的使用

    字面意思理解,转化流就是用来转化的,那么到底是什么转什么呢?我们可以通过以下的例子来熟悉。读取键盘输入的每一行内容,并写入到文本中,直到遇到over行结束输入

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    import java.io.*;

    public class TransStreamTest {

      

        public static void main(String[] args) throws IOException {

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\41639\\Desktop\\java\\temp\\test1031.txt"));

            String line =null;

            while ((line=br.readLine())!=null) {

                if ("over".contentEquals(line)) {

                    break;

                }

                bw.write(line);

                bw.newLine();

                bw.flush();

            }

        bw.close();

        br.close();

        }

      

    }

    2.InputStreamReader:输入流转到读流

    1

    2

    3

    4

    5

    String fileName= "d:"+File.separator+"hello.txt";

    File file=new File(fileName);

    Writer out=new OutputStreamWriter(new FileOutputStream(file));

    out.write("hello");

    out.close();

    3.OutputStreamWriter:输出流转到写流

    1

    2

    3

    4

    5

    6

    7

    String fileName= "d:"+File.separator+"hello.txt";

    File file=new File(fileName);

    Reader read=new InputStreamReader(new FileInputStream(file));

    char[] b=new char[100];

    int len=read.read(b);

    System.out.println(new String(b,0,len));

    read.close();

    以上就是java中字符流和字节流的替换方法,学会后当某一种用法不适用当前环境时,我们就可以把它进行另一种类型的转换,学会后就可以动手试验下了。

    专题推荐:java字符流和字节流替换
    上一篇:java IO字符流的用法 下一篇:java中File类的使用

    相关文章推荐

    • java中IO的分类• java IO流有几种• IO字节流在java中的使用• java IO字符流的用法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网