首页 > 编程语言 >Java IO

Java IO

时间:2023-11-16 21:44:55浏览次数:23  
标签:Java String IO file sb new public 读取

IO,即in和out,也就是输入和输出,指应用程序和外部设备之间的数据传递,常见的外部设备包括文件、管道、网络连接。
Java 中是通过流处理IO 的,那么什么是流?
流(Stream),是一个抽象的概念,是指一连串的数据(字符或字节),是以先进先出的方式发送信息的通道。
当程序需要读取数据的时候,就会开启一个通向数据源的流,这个数据源可以是文件,内存,或是网络连接。类似的,当程序需要写入数据的时候,就会开启一个通向目的地的流。这时候你就可以想象数据好像在这其中“流”动一样。
一般来说关于流的特性有下面几点:
   1. 先进先出:最先写入输出流的数据最先被输入流读取到。
   2.顺序存取:可以一个接一个地往流中写入一串字节,读出时也将按写入顺序读取一串字节,不能随机访问中间的数据。(RandomAccessFile除外)
   3.只读或只写:每个流只能是输入流或输出流的一种,不能同时具备两个功能,输入流只能进行读操作,对输出流只能进行写操作。在一个数据传输通道中,如果既要写入数据,又要读取数据,则要分别提供两个流。

FileInputStream、FileOutputStream(字节流)代码示例:

public class IOTest {
    public static void main(String[] args) throws IOException {
        File file = new File("D:/test.txt");

        write(file);
        System.out.println(read(file));
    }

    public static void write(File file) throws IOException {
        OutputStream os = new FileOutputStream(file, true);

        // 要写入的字符串
        String string = "松下问童子,言师采药去。只在此山中,云深不知处。";
        // 写入文件
        os.write(string.getBytes());
        // 关闭流
        os.close();
    }

    public static String read(File file) throws IOException {
        InputStream in = new FileInputStream(file);

        // 一次性取多少个字节
        byte[] bytes = new byte[1024];
        // 用来接收读取的字节数组
        StringBuilder sb = new StringBuilder();
        // 读取到的字节数组长度,为-1时表示没有数据
        int length = 0;
        // 循环取数据
        while ((length = in.read(bytes)) != -1) {
            // 将读取的内容转换成字符串
            sb.append(new String(bytes, 0, length));
        }
        // 关闭流
        in.close();

        return sb.toString();
    }
}

BufferedInputStream、BufferedOutputStream(缓冲字节流)

public class IOTest {

    public static void write(File file) throws IOException {
        // 缓冲字节流,提高了效率
        BufferedOutputStream bis = new BufferedOutputStream(new FileOutputStream(file, true));

        // 要写入的字符串
        String string = "松下问童子,言师采药去。只在此山中,云深不知处。";
        // 写入文件
        bis.write(string.getBytes());
        // 关闭流
        bis.close();
    }

    public static String read(File file) throws IOException {
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));

        // 一次性取多少个字节
        byte[] bytes = new byte[1024];
        // 用来接收读取的字节数组
        StringBuilder sb = new StringBuilder();
        // 读取到的字节数组长度,为-1时表示没有数据
        int length = 0;
        // 循环取数据
        while ((length = fis.read(bytes)) != -1) {
            // 将读取的内容转换成字符串
            sb.append(new String(bytes, 0, length));
        }
        // 关闭流
        fis.close();

        return sb.toString();
    }
}

InputStreamReader、OutputStreamWriter(字符流)

public class IOTest {
    
    public static void write(File file) throws IOException {
        // OutputStreamWriter可以显示指定字符集,否则使用默认字符集
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8");

        // 要写入的字符串
        String string = "松下问童子,言师采药去。只在此山中,云深不知处。";
        osw.write(string);
        osw.close();
    }

    public static String read(File file) throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
        // 字符数组:一次读取多少个字符
        char[] chars = new char[1024];
        // 每次读取的字符数组先append到StringBuilder中
        StringBuilder sb = new StringBuilder();
        // 读取到的字符数组长度,为-1时表示没有数据
        int length;
        // 循环取数据
        while ((length = isr.read(chars)) != -1) {
            // 将读取的内容转换成字符串
            sb.append(chars, 0, length);
        }
        // 关闭流
        isr.close();

        return sb.toString()
    }
}

BufferedReader、BufferedWriter(字符缓冲流)

public class IOTest {
    
    public static void write(File file) throws IOException {
        // BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new
        // FileOutputStream(file, true), "UTF-8"));
        // FileWriter可以大幅度简化代码
        BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));

        // 要写入的字符串
        String string = "松下问童子,言师采药去。只在此山中,云深不知处。";
        bw.write(string);
        bw.close();
    }

    public static String read(File file) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        // 用来接收读取的字节数组
        StringBuilder sb = new StringBuilder();

        // 按行读数据
        String line;
        // 循环取数据
        while ((line = br.readLine()) != null) {
            // 将读取的内容转换成字符串
            sb.append(line);
        }
        // 关闭流
        br.close();

        return sb.toString();
    }
}

 

标签:Java,String,IO,file,sb,new,public,读取
From: https://www.cnblogs.com/kandh/p/17837329.html

相关文章

  • Java常用类
    在学习使用Java语言时,我们常常要调用各种方法,而每个类里都有对应的方法,接下来介绍Java中一些常用类:- 1.String类eg.抽取身份证中的出生日期:Stringl="340822194510016411";System.out.print("出生日期是:");Sys......
  • Java数组03:三种初始化及内存分析
    声明的时候数组并不存在,只有创建的时候数组才存在  publicclassArrayDemo02{publicstaticvoidmain(String[]args){//静态初始化:创建+赋值int[]a={1,2,3,4,5,6,7,8};System.out.println(a[0]);//动态初始......
  • 无涯教程-Dart - Optional Parameters with Default Values函数
    默认情况下,还可以为函数参数分配值,但是,此类参数也可以是显式传递的值。语法function_name(param1,{param2=default_value}){//......}示例voidmain(){test_param(123);}voidtest_param(n1,{s1:12}){print(n1);print(s1);}它应该返回......
  • vue pinia sessionstorage 数据存储不上的原因
    vuepiniasessionstorage的坑默认的配置是开始localStorage如果用sessionstorage则发现数据存储不上,是因为缺少了序列化和反序列化import{parse,stringify}from'zipson'exportconstuseCounterStore=defineStore('counter',()=>{constcount=ref(0)......
  • Java数组02:数组的声明和创建
    ublicclassArrayDemo01{publicstaticvoidmain(String[]args){//数组类型int[]nums;//intnums[];声明一个数组nums=newint[10];//这里面可以存放10个int类型的数字;创建一个数组//给数组赋值for(inti=0;i<=9;+......
  • JavaWeb--响应字符&字节数据
    Response响应字符数据 //text/html解码html,charset解码汉字response.setContentType("text/html;charset=utf-8");//1、获取字符输入流PrintWriterwriter=response.getWriter();writer.write("你好");writer.write("<h1>124</h1>");响应字节数据添加一个i......
  • 11.16 基本完成个人任务管理系统项目后重新复习JavaScript高级程序设计——声明var与l
    我看的是js高级程序设计第四版,前两章快速了解了一下,第三章开始慢啃,虽然内容枯燥,很多东西自己也知道了,但还是有一些收获的。比如,声明变量的三个关键词:var、let、const;var以前经常用但是会出问题,相比let没有那么严谨(var声明范围函数作用域,而let声明范围块级作用域)。看个例子:这是v......
  • Vue3 Pinia对state的订阅监听($subscribe,$onAction)数据监听
    <template><divclass="main-container":class="{'show-scroll':targetIsVisible}"><div:style="{height:frameHeight+'px'}"class="main-content":class="{'show-......
  • Java方法06:递归讲解
     publicclassDemo05{publicstaticvoidmain(String[]args){//打印5的阶乘System.out.println(f(5));}publicstaticintf(intn){if(n==1){return1;}else{returnn*f(n-1);......
  • Java方法07:练习打一个计算器
    importjava.util.Scanner;publicclassDemo06{publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);Stringy="Y";while(y.equals("Y")){System.out.println(&quo......