栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

IO流在java中的实例操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

IO流在java中的实例操作

本教程操作环境: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类、字符流、缓冲流的知识点。对于这方面基础知识不够牢固的,可以在以往的内容中重新学习,然后进行实例的操作。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/15281.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号