java中io创建文件和读取文件
简单了解IO流:https://www.cnblogs.com/weibanggang/p/10034325.html
package com.wbg.iodemo1128; import java.io.*; public class OutputStreamDemo { public static void main(String[] args) throws IOException { reader(); } //输入字节流inputStream static void inputStream() throws IOException { File f=new File("F:"+File.separator+"test01.txt"); InputStream inputStream=new FileInputStream(f); byte b[]=new byte[1024]; inputStream.read(b); inputStream.close(); System.out.println(new String(b)); } //输出字节流OutputStream static void outputStream()throws IOException{ //第一步:使用File找到一个文件 File f=new File("F:"+File.separator+"test01.txt"); //创建文件 f.createNewFile(); //第二步:通过子类实例化父类对象 OutputStream out=new FileOutputStream(f); //第三步:写一个字符串 String str="Hello World!!!"; //第四步:字符串转为byte数组 byte b[]=str.getBytes(); //第五步:内容输出 out.write(b); //第六步:关闭 out.close(); } //字符流输出 static void writer() throws IOException { //第一步:使用File找到一个文件 File f=new File("f:"+File.separator+"test.txt"); //第二步:通过子类实例化父类对象 Writer out=new FileWriter(f); //追加 // Writer out=new FileWriter(f,true); //第三:定义字符串 String str="Hello,Word!!!"; //第四步:输出 out.write(str); //第五步:强制清空缓存 out.flush(); //第六步:关闭 out.close(); } //字符流正常输入 static void reader() throws IOException { //第一步:使用File找到一个文件 File f=new File("f:"+File.separator+"test.txt"); Reader readerout=new FileReader(f); int len=0; char[]c=new char[1024]; int temp=0; while ((temp=readerout.read())!=-1){ c[len]=(char)temp; len++; } readerout.close(); System.out.println(new String(c,0,len)); } //字符流输入追加 static void readerAdd() throws IOException { File f=new File("f:"+File.separator+"test.txt"); Reader reader=new FileReader(f); char[]c=new char[(int)f.length()]; reader.read(c); reader.close(); System.out.println(new String(c)); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下