File类示例

public class FileUsageTest {
private static void usage() {
System.err.println("Usage: FileUsageTest path1 ... \n" + "Creates each path\n"
+ "Usage: FileUsageTest -d path1 ...\n" + "Deletes each path\n"
+ "Usage: FileUsageTest -r path1 path2\n" + "Renames from path1 to path2");
System.exit(1);
} /**
* 获取文件元数据信息
*
* @param f
*/
private static void fileData(File f) {
System.out.println("Absolute Path: " + f.getAbsolutePath() + "\n Readable: " + f.canRead() + "\n Writable: " + f.canWrite()
+ "\n Name: " + f.getName() + "\n Parent Dir: " + f.getParent() + "\n Size: " + f.length() + "\n Last Modified: "
+ f.lastModified()); if (f.isFile()) {
System.out.println(f + " is a file");
} else if (f.isDirectory()) {
System.out.println(f + " is a directory");
}
} /**
* 通过传入参数控制功能
*
* @param args
*/
public static void main(String[] args) {
// 参数不符合要求
if (args.length < 1) {
usage();
} else if (args[0].equals("-r")) { // 重命名文件
if (args.length != 3)
usage();
File old = new File(args[1]);
File rname = new File(args[2]);
if (old.renameTo(rname)) {
System.out.println("Rename file " + old + " to " + rname + " successfully");
} else {
System.out.println("Rename file " + old + " to " + rname + " fail");
}
fileData(old);
fileData(rname);
} else if (args[0].equals("-d")) { // 依次删除文件
for (int i = 1; i < args.length; i++) {
File f = new File(args[i]); if (f.delete()) {
System.out.println(f + " exists");
System.out.println("Delete " + f + " successfully");
} else {
System.out.println("Delete " + f + " fail");
}
fileData(f);
}
} else { // 创建文件
for (String arg : args) {
File f = new File(arg); try {
if (f.createNewFile()) {
System.out.println("Created " + f + " successfully");
} else {
System.out.println("Created " + f + " fail");
}
} catch (IOException e) {
e.printStackTrace();
} fileData(f);
}
}
}
}

运行 java e:\\test\\testFile1 e:\\test\\testFile2

Created e:\test\testFile1 successfully
Absolute Path: e:\test\testFile1
Readable: true
Writable: true
Name: testFile1
Parent Dir: e:\test
Size: 0
Last Modified: 1378630413535
e:\test\testFile1 is a file
Created e:\test\testFile2 successfully
Absolute Path: e:\test\testFile2
Readable: true
Writable: true
Name: testFile2
Parent Dir: e:\test
Size: 0
Last Modified: 1378630413536
e:\test\testFile2 is a file

运行 java -r e:\\test\\testFile1 e:\\test\\testFile3

Rename file e:\test\testFile1 to e:\test\testFile3 successfully
Absolute Path: e:\test\testFile1
Readable: false
Writable: false
Name: testFile1
Parent Dir: e:\test
Size: 0
Last Modified: 0
Absolute Path: e:\test\testFile3
Readable: true
Writable: true
Name: testFile3
Parent Dir: e:\test
Size: 0
Last Modified: 1378630413535
e:\test\testFile3 is a file

运行 -d e:\\test\\testFile1 e:\\test\\testFile2

Delete e:\test\testFile1 fail
Absolute Path: e:\test\testFile1
Readable: false
Writable: false
Name: testFile1
Parent Dir: e:\test
Size: 0
Last Modified: 0
e:\test\testFile2 exists
Delete e:\test\testFile2 successfully
Absolute Path: e:\test\testFile2
Readable: false
Writable: false
Name: testFile2
Parent Dir: e:\test
Size: 0
Last Modified: 0

FilenameFilter示例

/**
* 用于File.list()方法回调的文件名过滤器
* 返回list()中自定义正则表达式匹配的文件名
*
* @author zhenwei.liu created on 2013 13-8-20 上午11:08
* @version $Id$
*/
public class RegxFilenameFilter implements FilenameFilter { private Pattern pattern; public RegxFilenameFilter(String regx) {
this.pattern = Pattern.compile(regx);
} @Override
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches();
} public static void main(String[] args) {
File path = new File("D:\\");
// 此处可以考虑使用匿名类解决问题
String[] list = path.list(new RegxFilenameFilter("\\w+"));
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for (String file : list) {
System.out.println(file);
} }
}

AliWangWang

CollabNet
data
Datagenerator
Evolus
Fiddler2
home
javalib
KuGou
mavenrepo
my_config_files

...

执行系统命令

public class OSExecute {
public static void command(String command) {
boolean err = false;
try {
// 执行命令
Process process = new ProcessBuilder(command.split(" ")).start(); String s;
// 获取标准输出
BufferedReader stdOut = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
while ((s = stdOut.readLine()) != null)
System.out.println(s); // 获取标准错误输出
BufferedReader errOut = new BufferedReader(new InputStreamReader(process.getErrorStream(), "GBK"));
while ((s = errOut.readLine()) != null) {
System.out.println(s);
err = true;
}
} catch (Exception e) {
if (!command.startsWith("CMD /C"))
command("CMD /C " + command);
else
throw new RuntimeException(e);
} if (err)
throw new OSExecuteException("Errors executing " + command);
} public static void main(String[] args) {
command("dir c:\\");
}
}

驱动器 C 中的卷没有标签。
卷的序列号是 C47F-784D

c:\ 的目录

2012/11/08 16:13 <DIR> Dell
2013/08/28 18:02 <DIR> IdeaProjects
2013/08/09 02:24 <DIR> Intel
2009/07/14 11:20 <DIR> PerfLogs
2013/09/03 16:19 <DIR> Program Files
2013/09/01 18:28 <DIR> Program Files (x86)
2013/07/24 23:50 <DIR> Ruby200-x64
2013/08/28 17:12 <DIR> svn_repository
2013/09/01 19:26 <DIR> Users
2013/09/04 22:22 <DIR> Windows
0 个文件 0 字节
10 个目录 77,945,860,096 可用字节

BufferedReader示例

public class BufferedReaderTest {
public static String read(String filename) throws IOException {
// 装饰器的使用
BufferedReader br = new BufferedReader(new FileReader(filename));
String s;
StringBuilder sb = new StringBuilder();
try {
while ((s = br.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} finally {
br.close();
}
return sb.toString();
} public static void main(String[] args) throws IOException {
System.out.println(read(Data.IN_FILE_PATH));
}
}

StringReader示例

public class StringReaderTest {

    public static void main(String[] args) throws IOException {
StringReader in = new StringReader(BufferedReaderTest.read(Data.IN_FILE_PATH));
int c;
try {
while ((c = in.read()) != -1) {
// 可以直接读取中文
System.out.print((char) c);
}
} finally {
in.close();
}
}
}

DataInputStream示例

/**
* DataInputStream主要用于读取格式化的int,long,byte等基本类型,并且这是平台无关的
*
* @author zhenwei.liu created on 2013 13-8-22 下午9:57
* @version $Id$
*/
public class DataInputStreamTest { public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(new ByteArrayInputStream(BufferedReaderTest.read(Data.IN_FILE_PATH)
.getBytes()));
try {
while (in.available() != 0) {
// 单字节读,中文会乱码
System.out.print((char) in.readByte());
}
} finally {
in.close();
}
}
}

PrintWriter示例

public class PrintWriterTest {

    public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(Data.IN_FILE_PATH));
// PrintWriter的便捷构造方法
// 等同于 new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))))
PrintWriter out = new PrintWriter(Data.OUT_FILE_PATH);
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(Data.OUT_FILE_PATH)));
String s;
int lineCount = 0;
try {
while ((s = in.readLine()) != null) {
out.println(++lineCount + " : " + s);
}
} finally {
out.close();
in.close();
} System.out.println(BufferedReaderTest.read(Data.OUT_FILE_PATH));
}
}

System.in示例

/**
* System.in测试,回显输入的每一行
*
* @author zhenwei.liu created on 2013 13-8-24 下午1:12
* @version $Id$
*/
public class SystemInTest { public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
try {
while ((s = in.readLine()) != null && !s.equals(""))
System.out.println(s);
} finally {
in.close();
} }
}

System.out示例

public class SystemOutTest {

    public static void main(String[] args) {
PrintWriter printWriter = new PrintWriter(System.out, true);
printWriter.println("I'm System.out");
}
}

Java IO的简单示例的更多相关文章

  1. Java IO流简单使用

    Java IO流简单使用 也许是以前IO方面接触的比较少,我对于读和写的概念老是混淆. 趁着现在实习比较闲小结一下,我个人理解读和写都是针对程序,分别就是程序的输入和输出,或者叫读入写出. Java ...

  2. Java IO之简单输入输出

    Java中的IO分为两个部分,以InputStream和Reader为基类的输入类,以OutputStream和Writer为基类的输出类. 当中InputStream和OutputStream以字节 ...

  3. Java操作redis简单示例

    第一:安装Redis    首先我们要安装Redis,就像我们操作数据库一样,在操作之前肯定要先创建好数据库的环境.    Redis的下载可以百度一下,或者打开下面的下载链接:    https:/ ...

  4. java IO类简单介绍

    一.流的概念 流是字节序列的抽象概念.流和文件的差别:文件是数据的静态存储形式,而流是指数据传输时的形态.文件只是流的操作对象之一.流按其操作的对象不同可以分为文件流.网络流.内存流.磁带流等.Jav ...

  5. Java基础 while 简单示例

        JDK :OpenJDK-11      OS :CentOS 7.6.1810      IDE :Eclipse 2019‑03 typesetting :Markdown   code ...

  6. Java基础 switch 简单示例

        JDK :OpenJDK-11      OS :CentOS 7.6.1810      IDE :Eclipse 2019‑03 typesetting :Markdown   code ...

  7. Java基础 do-while 简单示例

        JDK :OpenJDK-11      OS :CentOS 7.6.1810      IDE :Eclipse 2019‑03 typesetting :Markdown   code ...

  8. 【java】反射简单示例

    package 反射; public class Test反射 { public static void main(String[] args) { System.out.println(Runtim ...

  9. 【java】正则表达式简单示例

    public class Test { public static void main(String[] args) { String str="135axy"; String r ...

随机推荐

  1. Wannafly挑战赛9 D - 造一造

    链接:https://www.nowcoder.com/acm/contest/71/D来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K,其他语言52428 ...

  2. 【记录】【持续更新】mybatis使用记录

    1.>  < 等符号在mybatis中的sql语句需要转义 > : > < : < 2.mybatis动态选择 <choose> <when te ...

  3. 五、django rest_framework源码之版本控制剖析

    1 绪论 Djangorest_framework的版本控制允许用户更改不同客户端之间的行为,且提供了许多不同的版本控制方案.版本控制由传入的客户端请求确定,可以基于请求URL,也可以基于请求标头. ...

  4. JAVAEE——宜立方商城08:Zookeeper+SolrCloud集群搭建、搜索功能切换到集群版、Activemq消息队列搭建与使用

    1. 学习计划 1.solr集群搭建 2.使用solrj管理solr集群 3.把搜索功能切换到集群版 4.添加商品同步索引库. a) Activemq b) 发送消息 c) 接收消息 2. 什么是So ...

  5. Ace-editor 输入内容时光标闪动,定位错乱的解决方案

    请尝试将字体设置成12PX或者14px(偶数),避免设置成13px. 应该就可以解决. 同时向大家推荐一款可直接生成文档的API调试.管理工具(中文PostMAN):https://www.apipo ...

  6. Initializing the FallBack certificate failed . TDSSNIClient initialization failed

    安装SQL后服务不能启动,报错: 2014-03-24 14:33:10.06 spid13s     Error: 17190, Severity: 16, State: 1.2014-03-24 ...

  7. http常见请求头与响应头

    1.HTTP常见的请求头 If-Modified-Since:把浏览器端缓存页面的最后修改时间发送到服务器去,服务器会把这个时间与服务器上实际文件的最后修改时间进行对比.如果时间一致,那么返回304, ...

  8. C# 简单读写ini文件帮助类 INIHelp

    软件里需要读取一些初始化信息, 决定用ini来做,简单方便. 于是查了一写代码,自己写了一个帮助类. INI文件格式是某些平台或软件上的配置文件的非正式标准, 以节(section)和键(key)构成 ...

  9. luoguP4555 [国家集训队]最长双回文串 manacher算法

    不算很难的一道题吧.... 很容易想到枚举断点,之后需要处理出以$i$为开头的最长回文串的长度和以$i$为结尾的最长回文串的长度 分别记为$L[i]$和$R[i]$ 由于求$R[i]$相当于把$L[i ...

  10. php安装编译时 configure: error: Cannot find OpenSSL's <evp.h>

    =============================================== yum install error: protected multilib versions error ...