Java读取文件内容的六种方法(详细教程)
第一种FileInputStream 文件读取
FileInputStream inputStream = null; try {
File file = new File("file.txt"); inputStream = new FileInputStream(file); int content; while ((content = inputStream.read()) != -1) {
// 处理读取到的字节 } } catch (IOException e) {
e.printStackTrace(); } finally {
if (inputStream != null) {
try {
inputStream.close(); } catch (IOException e) {
e.printStackTrace(); } } }
讯享网
BufferedReader:文件读取
讯享网BufferedReader reader = null; try {
File file = new File("file.txt"); FileReader fileReader = new FileReader(file); reader = new BufferedReader(fileReader); String content; while ((content = reader.readLine()) != null) {
// 处理读取到的一行字符串 } } catch (IOException e) {
e.printStackTrace(); } finally {
if (reader != null) {
try {
reader.close(); } catch (IOException e) {
e.printStackTrace(); } } }
文件写入FileOutputStream:
FileOutputStream outputStream = null; try {
File file = new File("file.txt"); outputStream = new FileOutputStream(file); String content = "Hello, world!"; byte[] bytes = content.getBytes(); outputStream.write(bytes); } catch (IOException e) {
e.printStackTrace(); } finally {
if (outputStream != null) {
try {
outputStream.close(); } catch (IOException e) {
e.printStackTrace(); } } }
PrintWriter:文件写入
讯享网PrintWriter writer = null; try {
File file = new File("file.txt"); FileWriter fileWriter = new FileWriter(file); writer = new PrintWriter(fileWriter); String content = "Hello, world!"; writer.println(content); } catch (IOException e) {
e.printStackTrace(); }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/29307.html