欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > Java File IO

Java File IO

2025/5/15 22:00:10 来源:https://blog.csdn.net/weixin_64260010/article/details/139575612  浏览:    关键词:Java File IO

Java File IO

~主要介绍四个类 InputStream OutputStream FileReader FileWriter~

InputStream (字节流读取File)

 public static void main(String[] args) throws IOException {String filePath = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileInputStream fileInputStream = new FileInputStream(filePath);int read;//如果读到的是-1就说明没有了 读完了while ((read = fileInputStream.read())!= -1){System.out.print((char)read);}}

OutputStream(字节流写入File)

public static void main(String[] args) throws IOException {String filePath = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileOutputStream fileOutputStream = new FileOutputStream(filePath,true);String outPut = "sadfasd";fileOutputStream.write(outPut.getBytes());fileOutputStream.close();}

FileReader(字符流读取File)

 public static void main(String[] args) throws IOException {String filePath = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileReader fileReader = new FileReader(filePath);int readLean = 0; //读取的字符串长度char[] charBuf = new char[8];while ((readLean = fileReader.read(charBuf)) != -1){System.out.print(new String(charBuf, 0, readLean));}}

注:这个方法可以读取汉字

 public static void main(String[] args) throws IOException {String filePath = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileReader fileReader = new FileReader(filePath);int read = 0;while ((read = fileReader.read()) != -1){System.out.print((char)read);}}

注:这个方法效率低

FileWriter(字符流写入File)

public static void main(String[] args) throws IOException {String filePtah = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileWriter fileWriter = new FileWriter(filePtah, true); //加true是追加 不加是覆盖String write = "哈哈哈";fileWriter.write(write.toCharArray()); //write(int)//write(char[])//write(char[], off, len)//write(sring)//write(string,off,len) fileWriter.close(); //一定要关闭 不然的话写不进去}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词