建设一个商务网站的步骤,用mvc做网站报告,福田网络推广公司,wordpress主题white文章目录 InputStream和ReaderScannerNIO外传 一般读取文件类的使用字符流即可
InputStream和Reader
InputStream和Reader是Java IO中的两个重要的抽象基类#xff0c;InputStream是二进制流#xff0c;Reader是字符流。使用InputStream或者Reader读取文件内容可以帮助我们… 文章目录 InputStream和ReaderScannerNIO外传 一般读取文件类的使用字符流即可
InputStream和Reader
InputStream和Reader是Java IO中的两个重要的抽象基类InputStream是二进制流Reader是字符流。使用InputStream或者Reader读取文件内容可以帮助我们读取文本文件非二进制文件的内容。
下面是一个使用Reader读取文件内容的示例代码 File file new File(test.txt);
try {FileReader reader new FileReader(file);BufferedReader br new BufferedReader(reader);String str;while ((str br.readLine()) ! null) {System.out.println(str);}br.close();reader.close();
} catch (IOException e) {e.printStackTrace();
}使用FileReader类读取文件内容并将FileReader对象传入BufferedReader类中以便于一次读取一行然后逐行读取并输出文件内容。
Scanner
Scanner是Java内置的一个读取用户输入的类他也可以用于读取文件内容。使用Scanner读取文件内容需要先创建File对象并将其传入Scanner构造函数中。
下面是一个使用Scanner读取文件内容的示例代码
File file new File(test.txt);
try {Scanner scanner new Scanner(file);while (scanner.hasNextLine()) {System.out.println(scanner.nextLine());}scanner.close();
} catch (FileNotFoundException e) {e.printStackTrace();
}使用Scanner类读取文件内容并通过while循环和hasNextLine()方法逐行读取文件内容并输出到控制台。
NIO
Java NIO(New IO)是从Java 1.4开始引入的一组新IO API。相较于之前的IO APINIO提供了更高效的IO操作和更多的控制选项。下面是一个使用NIO读取文件内容的示例代码
File file new File(test.txt);
try {FileInputStream fileInputStream new FileInputStream(file);FileChannel fileChannel fileInputStream.getChannel();ByteBuffer byteBuffer ByteBuffer.allocate((int) file.length());fileChannel.read(byteBuffer);byteBuffer.flip();byte[] bytes byteBuffer.array();System.out.println(new String(bytes, 0, bytes.length));fileInputStream.close();
} catch (IOException e) {e.printStackTrace();
}使用FileInputStream读取文件内容并调用getChannel()方法获取FileChannel对象然后调用read()方法将文件内容读入到ByteBuffer缓冲区中。最后通过flip()方法将缓冲区设置为读模式并通过byteBuffer.array()将缓冲区中的内容转换为字节数组再通过new String()方法将字节数组转换为字符串并输出到控制台。
外传 原创不易如若本文能够帮助到您的同学支持我关注我点赞收藏⭐️留言探讨问题看到立马回复格言己所不欲勿施于人 扬帆起航、游历人生、永不言弃