简而言之Java.io:22个案例研究

这篇文章试图涵盖java.io中的一整套操作。 与与此主题相关的其他书籍和博客相比,我的动机是通过案例研究展示“操作方法”。 作为一名Java的学生,我意识到学习一种新的程序语言的最有效方法是通过示例:复制并粘贴一段代码,运行它以查看结果,然后尝试逐步修改并重新运行它。 。 因此,我认为这篇文章会有所帮助。

值得注意的是,本文不会涉及与java.nio相关的任何内容,因为我认为这是一个完全不同的主题。

目录

  • 情况0:创建一个新文件
  • 情况1:File中的两个常量
  • 情况2:删除文件
  • 情况3:创建目录
  • 情况4:列出给定目录中的文件和目录
  • 情况5:测试文件是否为文件
  • 情况6:写入RandomAccessFile
  • 情况7:将字节写入文件
  • 情况8:将字节追加到文件
  • 情况9:从文件读取字节
  • 情况10:复制文件
  • 情况11:将字符写入文件
  • 情况12:从文件中读取字符
  • 情况13:从OutputStream转换为FileWriter
  • 情况14:从InputStream转换为FileReader
  • 案例15:使用管道
  • 情况16:将格式化的字符串写入文件
  • 案例17:重定向“标准” IO
  • 情况18:逐行读取文件
  • 案例19:压缩到一个zip文件
  • 案例20:从zip文件中提取
  • 情况21:推回字节

情况0:创建一个新文件

import java.io.File;
public class FileOperationTest {public static void main(String[] args) {File f = new File("helloworld.txt");try {f.createNewFile();} catch (Exception e) {e.printStackTrace();}}
}

输出: 如果之前没有“ helloword.txt”,则在工作目录中创建一个新的空文件。

情况1:File中的两个常量

import java.io.File;
public class FileOperationTest {public static void main(String[] args) {System.out.println(File.separator);System.out.println(File.pathSeparator);}
}

输出:

/
:

我得到上面的输出,因为我正在Linux上工作。 如果使用Windows,则输出应为\; 。 可以看出,出于可移植性和鲁棒性的目的,应始终建议使用这两个常量。

情况2:删除文件

import java.io.File;
public class FileOperationTest {public static void main(String[] args) {File f = new File("helloworld.txt");if (f.exists()) {if (!f.delete()) {System.out.println("the file cannot be deleted.");}} else {System.out.println("the file does not exist.");}}
}

情况3:创建目录

import java.io.File;
public class FileOperationTest {public static void main(String[] args) {File f = new File("hello");f.mkdir();}
}

情况4:列出给定目录中的文件和目录

import java.io.File;
public class FileOperationTest {public static void main(String[] args) {File f = new File(".");for (String str : f.list()) {System.out.println(str);}}
}

输出:我正在使用Eclipse

.settings
.classpath
.project
src
bin

文件list()返回一个字符串数组。 如果您更喜欢File的数组,请使用FilelistFiles()

import java.io.File;
public class FileOperationTest {public static void main(String[] args) {File f = new File(".");for (File subFile : f.listFiles()) {System.out.println(subFile.getName());}}
}

情况5:测试文件是否为文件

import java.io.File;
public class FileOperationTest {public static void main(String[] args) {File f = new File("helloworld.txt");if (f.isFile()) {System.out.println("YES");} else {System.out.println("NO");}}
}

File结合。 listFiles() ,我们可以列出给定目录及其子目录中的所有文件。

import java.io.File;public class FileOperationTest {public static void main(String[] args) {File f = new File(".");listFiles(f);}private static void listFiles(File f) {if (f.isFile()) {System.out.println(f.getName());return;}for (File subFile : f.listFiles()) {listFiles(subFile);}}
}

输出:案例4进行比较以查看差异

org.eclipse.jdt.core.prefs
.classpath
.project
FileOperationTest.java
FileOperationTest.class

情况6:写入RandomAccessFile

import java.io.IOException;
import java.io.RandomAccessFile;public class FileOperationTest {public static void main(String[] args)throws IOException {RandomAccessFile file = new RandomAccessFile("helloworld.txt", "rw");file.writeBytes("hello world!");file.writeChar('A');file.writeInt(1);file.writeBoolean(true);file.writeFloat(1.0f);file.writeDouble(1.0);file.close();}
}

如果使用文本编辑器打开文件,则会发现乱码,除了第一个hello world!A (请注意,在“ hello world!”末尾的char A )。 这是因为RandomAccessFile仅在文件中写入字节数组。

情况7:将字节写入文件

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {OutputStream out = new FileOutputStream("helloworld.txt");String str = "hello world!";out.write(str.getBytes());out.close();}
}

这次您可以看到“你好,世界!” 在文件中。 当然,您可以逐字节写入OutputStream ,但是效率较低:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {OutputStream out = new FileOutputStream("helloworld.txt");String str = "hello world!";for (byte b : str.getBytes()) {out.write(b);}out.close();}
}

情况8:将字节追加到文件

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {OutputStream out = new FileOutputStream("helloworld.txt", true);String str = "hello world!";out.write(str.getBytes());out.close();}
}

输出: hello world!hello world!

情况9:从文件读取字节

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {InputStream in = new FileInputStream("helloworld.txt");byte[] bs = new byte[1024];int len = -1;while ((len = in.read(bs)) != -1) {System.out.println(new String(bs, 0, len));}in.close();}
}

InputStream 。 如果到达文件末尾, read()将返回-1。 否则,它将返回读入缓冲区的字节总数。

情况10:复制文件

简单地结合案例79 ,我们将获得复制功能。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;public class Copy {public static void main(String[] args)throws IOException {if (args.length != 2) {System.out.println("java Copy SOURCE DEST");System.exit(1);}InputStream input = new FileInputStream(args[0]);OutputStream output = new FileOutputStream(args[1]);int len = 0;byte bs[] = new byte[1024];while ((len = input.read(bs)) != -1) {output.write(bs, 0, len);}input.close();output.close();}
}

情况11:将字符写入文件

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;public class FileOperationTest {public static void main(String[] args)throws IOException {Writer out = new FileWriter("helloworld.txt");String str = "hello world!";out.write(str);out.close();}
}

对于上述情况,您将获得与案例7相同的结果。 那么区别是什么呢? FileWriter用于编写字符流。 它将使用默认的字符编码和默认的字节缓冲区大小。 换句话说,为方便起见,它是FileOutputStream的包装器类。 因此,要自己指定这些值,请考虑使用FileOutputStream

情况12:从文件中读取字符

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;public class FileOperationTest {public static void main(String[] args)throws IOException {Reader in = new FileReader("helloworld.txt");char cs[] = new char[1024];int len = -1;while ((len = in.read(cs)) != -1) {System.out.println(new String(cs, 0, len));}in.close();}
}

是否使用字节流或字符流? 真的要看 两者都有缓冲区。 InputStream / OutputStream提供了更大的灵活性,但会使您的“简单”程序变得复杂。 另一方面,FileWriter / FileReader提供了一个整洁的解决方案,但是您失去了控制权。

情况13:从OutputStream转换为FileWriter

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;public class FileOperationTest {public static void main(String[] args)throws IOException {Writer out = new OutputStreamWriter(new FileOutputStream("helloworld.txt"));out.write("hello world!");out.close();}
}

您可以指定字符集,而不是使用默认字符编码。 例如,

Writer out = new OutputStreamWriter(new FileOutputStream("helloworld.txt"), "utf8");

情况14:从InputStream转换为FileReader

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;public class FileOperationTest {public static void main(String[] args)throws IOException {Reader in = new InputStreamReader(new FileInputStream("helloworld.txt"));char cs[] = new char[1024];int len = -1;while ((len = in.read(cs)) != -1) {System.out.println(new String(cs, 0, len));}in.close();}
}

案例15:使用管道

以下代码创建了两个线程,一个生产者在一端将内容写入管道,而另一个消费者从另一端从管道读取该线程。 要创建管道,我们需要分别创建PipedInputStreamPipedOutputStream ,并使用output.connect(input)或通过其构造函数进行连接。 在此程序中,我有意先启动Consumer线程,并在启动Producer线程之前让整个程序休眠1秒。 这将显示管道确实起作用。 值得注意的是,我关闭了Producer中的管道,因为“ 写入流的线程应始终在终止之前关闭OutputStream。 ”如果我们删除out.close()行,将抛出IOException

java.io.IOException: Write end deadat java.io.PipedInputStream.read(PipedInputStream.java:311)at java.io.PipedInputStream.read(PipedInputStream.java:378)at java.io.InputStream.read(InputStream.java:101)at foo.Consumer.run(FileOperationTest.java:58)at java.lang.Thread.run(Thread.java:701)
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException, InterruptedException {PipedInputStream input = new PipedInputStream();PipedOutputStream output = new PipedOutputStream();output.connect(input);Producer producer = new Producer(output);Consumer consumer = new Consumer(input);new Thread(consumer).start();Thread.sleep(1000);new Thread(producer).start();}
}class Producer implements Runnable {private final OutputStream out;public Producer(OutputStream out) {this.out = out;}@Overridepublic void run() {String str = "hello world!";try {out.write(str.getBytes());out.flush();out.close();} catch (Exception e) {e.printStackTrace();}}
}class Consumer implements Runnable {private final InputStream in;public Consumer(InputStream in) {this.in = in;}@Overridepublic void run() {byte[] bs = new byte[1024];int len = -1;try {while ((len = in.read(bs)) != -1) {System.out.println(new String(bs, 0, len));}} catch (IOException e) {e.printStackTrace();}}
}

情况16:将格式化的字符串写入文件

PrintStream添加了一些功能,可以方便地打印各种数据值的表示形式。 格式字符串的语法与C几乎相同。

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;public class FileOperationTest {public static void main(String[] args)throws IOException {PrintStream print = new PrintStream(new FileOutputStream("helloworld.txt"));print.printf("%s %s!", "hello", "world");print.close();}
}

案例17:重定向“标准” IO

在Java中,标准输出和错误输出均为PrintStream 。 标准输入是InputStream 。 因此,我们可以自由地重新分配它们。 以下代码将标准输出重定向到错误输出。

public class FileOperationTest {public static void main(String[] args) {System.out.println("hello world!");System.setOut(System.err);System.out.println("hello world!");}
}

输出:在Eclipse中,红色文本表示错误消息

hello world!hello world!

情况18:逐行读取文件

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;public class FileOperationTest {public static void main(String[] args)throws IOException {BufferedReader reader = new BufferedReader(new FileReader("helloworld.txt"));String str = null;while ((str = reader.readLine()) != null) {System.out.println(str);}reader.close();}
}

案例19:压缩到一个zip文件

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("helloworld.zip"));String str = "hello world!";for (int i = 0; i < 3; i++) {zipOut.putNextEntry(new ZipEntry("helloworld" + i + ".txt"));zipOut.write(str.getBytes());zipOut.closeEntry();}zipOut.close();}
}

上面的代码创建了一个zip文件,并放置了三个文件,分别名为“ helloworld0.txt”,“ helloworld1.txt”和“ helloworld2.txt”,每个文件都包含内容“ hello world!”。

案例20:从zip文件中提取

import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {ZipInputStream zipIn = new ZipInputStream(new FileInputStream("helloworld.zip"));ZipEntry entry = null;byte bs[] = new byte[1024];while ((entry = zipIn.getNextEntry()) != null) {// get file nameSystem.out.printf("file: %s content: ", entry.getName());int len = -1;// read current entry to the bufferwhile((len=zipIn.read(bs)) != -1) {System.out.print(new String(bs, 0, len));}System.out.println();}zipIn.close();}
}

输出:

file: helloworld0.txt content: hello world!
file: helloworld1.txt content: hello world!
file: helloworld2.txt content: hello world!

情况21:推回字节

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {PushbackInputStream push = new PushbackInputStream(new ByteArrayInputStream("hello, world!".getBytes()));int temp = 0;while ((temp = push.read()) != -1) {if (temp == ',') {push.unread('.');}System.out.print((char) temp);}}
}

上面的代码在读取逗号后按了一个点,因此输出为

hello,. world!

但是,如果您尝试向后推更多字符,例如push.unread("(...)".getBytes()); ,您将获得IOException :推回缓冲区已满。 这是因为推回缓冲区的默认大小为1。要指定更大的容量,请使用构造函数PushbackInputStream(InputStream in, int size) ,例如

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {PushbackInputStream push = new PushbackInputStream(new ByteArrayInputStream("hello, world!".getBytes()), 10);int temp = 0;while ((temp = push.read()) != -1) {if (temp == ',') {push.unread("(...)".getBytes());}System.out.print((char) temp);}}
}

输出:

hello,(...) world!

参考: 简而言之 Java.io:PGuru博客上来自我们的JCG合作伙伴 Peng Yifan的 22个案例研究 。

翻译自: https://www.javacodegeeks.com/2013/12/java-io-in-nutshell-22-case-studies.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/366159.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php gps 坐标,php 计算gps坐标 距离

在计算机或GPS上经纬度经常用度、分、秒和度.度、分.分、秒.秒的混合方式进行表示&#xff0c;度、分、秒间的进 制是60进制&#xff0c;度.度、分.分、秒.秒的进制是100进制&#xff0c;换算时一定要注意。可以近似地认为每个纬度之间的距离是不变的111KM,每分间 1.85KM&#…

博客园如何使用MarkDown

如何使用博客园下的markdown&#xff1a;https://www.cnblogs.com/ulrica/p/8933549.html 博客园的 MarkDown 代码样式如何设置https://www.cnblogs.com/zhongxia/p/26b4b061f2a47518681bcdd4ff89c344.html 博客园 Markdown 编辑器指南http://www.cnblogs.com/qiaogaojian/p/61…

jQuery -- 光阴似箭(五):AJAX 方法

jQuery -- 知识点回顾篇&#xff08;五&#xff09;&#xff1a;AJAX 方法 1. $.ajax 方法&#xff1a;用于执行 AJAX&#xff08;异步 HTTP&#xff09;请求。 <!DOCTYPE html> <html> <head> <meta http-equiv"Content-Type" content"t…

ggplot2设置坐标轴范围_R语言数据可视化| ggplot2中会“分身术”的facet_wrap()与facet_grid()...

【R语言】高维数据可视化| ggplot2中会“分身术”的facet_wrap()与facet_grid()姐妹花​mp.weixin.qq.comfacet_grid()形成由行和列面化变量定义的面板矩阵。当有两个离散变量&#xff0c;并且这些变量的所有组合存在于数据中时&#xff0c;它是最有用的。如果只有一个具有多个…

使用Google GSON:额外的赠品:第一部分

介绍 这是以前的Google GSON入门的后续文章&#xff0c;其中显示了有关使用Google Gson的入门资料。 本文显示了GSON库的一些其他优点。 由于有很多关于这些额外功能的文章要写&#xff0c;所以我将长篇文章分成2个系列&#xff0c;因此&#xff0c;这是其中一部分&#xff0c…

HDU 2181 哈密顿绕行世界问题 (dfs)

哈密顿绕行世界问题 Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Submit Status Description 一个规则的实心十二面体&#xff0c;它的 20个顶点标出世界著名的20个城市&#xff0c;你从一个城…

php resque 计划任务,PHP-RESQUE - 实现重试

因为PHP-Resque 的重试部分需要自己写&#xff0c;网上又没啥轮子&#xff0c;而且resque也已经很久不更新了&#xff0c;所以自己研究下resque的源码&#xff0c;然后也借鉴了Laravel的队列重试机制&#xff0c;实现了PHP-Resque的重试机制。Resque地址设计思路1.这里需要阅读…

RabbitMQ集群、镜像部署配置

1 RABBITMQ简介及安装 RabbitMQ是一个开源的AMQP实现&#xff0c;服务器端用Erlang语言编写&#xff0c;支持多种客户端&#xff0c;如&#xff1a;Python、Ruby、.NET、Java、JMS、C、PHP、ActionScript、XMPP、STOMP等&#xff0c;支持AJAX。用于在分布式系统中存储转发消息…

C语言、c++实现超好玩植物大战僵尸(完整版附源码)

实现这个游戏需要Easy_X main.cpp //开发日志 //1导入素材 //2实现最开始的游戏场景 //3实现游戏顶部的工具栏 //4实现工具栏里面的游戏卡牌 #define WIN_WIDTH 900 #define WIN_HEIGHT 600 //定义植物类型 enum { WAN_DOU, XIANG_RI_KUI, ZHI_WU_COUNT }; #include<stdio.…

【代码笔记】Web-HTML-颜色

一&#xff0c;效果图。 二&#xff0c;代码。 <!DOCTYPE html> <html> <head> <meta charset"utf-8"> <title>html 颜色</title> </head> <body> <!--html 颜色--> <p style"">> 通过十六…

java 如何去掉http debug日志_你居然还去服务器上捞日志,搭个日志收集系统难道不香吗?...

作者&#xff1a;MacroZheng链接&#xff1a;https://juejin.im/post/5eef217d51882565d74fb4eb来源&#xff1a;掘金SpringBoot实战电商项目mall&#xff08;35kstar&#xff09;地址&#xff1a;http://github.com/macrozheng/…摘要ELK日志收集系统进阶使用&#xff0c;本文…

GitHub的10,000个最受欢迎的Java项目-以下是它们使用的顶级库

随着Java开发人员正在使用既成熟又高度发展的语言来工作&#xff0c;无论何时编写新代码&#xff0c;我们都将面临一个持续的难题–使用大家都在谈论的热门新技术&#xff0c;或者坚持使用久经考验的库&#xff1f; 由于Java应用程序的很大一部分是商业性质的&#xff0c;因此…

JavaScript 事件机制(四)

JavaScript 事件机制 1 什么是事件 JavaScript 使我们有能力创建动态页面。事件是可以被 JavaScript 侦测到的行为。 网页中的每个元素都可以产生某些可以触发 JavaScript 函数的事件。比方说&#xff0c;我们可以在用户点击某按钮时产生一个 onClick 事件来触发某个函数。事件…

php设计是什么意思,php – 什么是更好的设计?

我有以下课程&#xff1a;class User {public function setName($value) { ... }public function setEmailAddress($value) { ... }public function setUsername($value) { ... }public function getName() { ... }public function getEmailAddress() { ... }public function g…

JavaScript——根据数组中的某个值进行排序

我这里是根据次数进行倒叙,可根据自己情况进行修改 function sortKey(array,key){return array.sort(function(a,b){var x a[key];var y b[key];return ((x>y)?-1:(x<y)?1:0)}) }; 转载于:https://www.cnblogs.com/wangyang0210/p/10185494.html

Java防止Xss注入json_每日一题(java篇) 如何防止xss注入

1、XssAndSqlHttpServletRequestWrapper 类&#xff1a;import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class XssAndSqlHttpServletRequestWrapper extends HttpServletReques…

【工具相关】web-HTML/CSS/JS Prettify的使用

一&#xff0c;打开Sublime Text,代码如下面所示。 二&#xff0c;鼠标右键--->HTML/CSS/JS Prettify--->Prettify Code.代码如图所示&#xff0c;明显的代码变得整齐了。 更多专业前端知识&#xff0c;请上 【猿2048】www.mk2048.com

centos 多个mysql,Centos中安装多个MySQL数据的配置实例

这篇文章主要为大家详细介绍了Centos中安装多个MySQL数据的配置实例&#xff0c;具有一定的参考价值&#xff0c;可以用来参考一下。感兴趣的小伙伴&#xff0c;下面一起跟随512笔记的小编小韵来看看吧&#xff01;注:本文档做了两个MYSQL实例,多个实例方法以此类推LINUX操作系…

MS SQL 分页存储过程

最近换了家新公司&#xff0c;但是新公司没有使用分页的存储过程。那我就自个写一个往项目上套 &#xff08;效率怎么样就不怎么清楚没有详细的测试过&#xff09; CREATE PROCEDURE [dbo].[pro_common_pageList](tab NVARCHAR(MAX) ,---表名PrimaryKey VARCHAR(100) , --主键I…

了解Spring Web初始化

几年前&#xff0c;我们大多数人习惯到处编写XML配置文件&#xff0c;甚至可以设置简单的Java EE应用程序。 如今&#xff0c;使用Java或Groovy来配置项目已成为一种首选方式–您只需要看一下Spring框架的其他版本中引入的Gradle或功能&#xff0c;就可以对此进行总结。 现在&…