品易云推流 关闭
文章详情页
文章 > java基础 > IO流在java中的实例操作

IO流在java中的实例操作

头像

小妮浅浅

2021-02-09 13:59:461815浏览 · 0收藏 · 0评论

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

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图