IO流在java中的实例操作

2026-01-29 0 40,046

本教程操作环境:windows7系统、java10版,DELL G3电脑。

1.使用FileInputStream,从文件读取数据

import java.io.*;
public class TestFileImportStream {
 
public static void main(String[] args) {
int b=0;
FileInputStream in = null;
try {
in =new FileInputStream("C:\Users\41639\Desktop\java\FileText\src\TestFileImportStream.java");
}catch(FileNotFoundException e){
System.out.println("file is not found");
System.exit(-1);
}
try {
long num=0;
while ((b=in.read())!=-1) {
System.out.println((char)b);
num++;
}
in.close();
System.out.println();
System.out.println("共读取了"+num+"个字节");
}catch(IOException e) {
System.out.println("IO异常,读取失败");
System.exit(-1);
}
}

2.字符流便捷类

Java提供了FileWriter和FileReader简化字符流的读写,new FileWriter等同于new OutputStreamWriter(new FileOutputStream(file, true))

public class IOTest {
public static void write(File file) throws IOException {
FileWriter fw = new FileWriter(file, true);
 
// 要写入的字符串
String string = "松下问童子,言师采药去。只在此山中,云深不知处。";
fw.write(string);
fw.close();
}
 
public static String read(File file) throws IOException {
FileReader fr = new FileReader(file);
// 一次性取多少个字节
char[] chars = new char[1024];
// 用来接收读取的字节数组
StringBuilder sb = new StringBuilder();
// 读取到的字节数组长度,为-1时表示没有数据
int length;
// 循环取数据
while ((length = fr.read(chars)) != -1) {
// 将读取的内容转换成字符串
sb.append(chars, 0, length);
}
// 关闭流
fr.close();
 
return sb.toString();
}
}

3.使用缓冲区从键盘上读入内容

public static void main(String[] args) throws IOException {
 
        BufferedReader buf = new BufferedReader(
                new InputStreamReader(System.in));
        String str = null;
        System.out.println("请输入内容");
        try{
            str = buf.readLine();
        }catch(IOException e){
            e.printStackTrace();
        }
        System.out.println("你输入的内容是:" + str);
}

以上就是IO流在java中的实例操作,涉及到File类、字符流、缓冲流的知识点。对于这方面基础知识不够牢固的,可以在以往的内容中重新学习,然后进行实例的操作。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 java教程 IO流在java中的实例操作 https://www.zhiup.top/11127.html

相关