1.文件操作
<span style="font-family:Times New Roman;font-size:18px;">import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) throws IOException {
//以当前路径创建一个File对象
File file=new File(".");
//直接获取文件名,输出一点
System.out.println(file.getName());
//获取相对路径的父路径可能出错,下面代码输出null
System.out.println(file.getParent());
//获取绝对路径
System.out.println(file.getAbsoluteFile());
//获取上一级路径
System.out.println(file.getAbsoluteFile().getParent());
//在当前目录下创建一个临时文件
File tmpFile=File.createTempFile("aaa", ".txt",file);
//指定当JVM退出时删除该文件
//tmpFile.deleteOnExit();
//以系统当前时间作为新文件名来创建新文件
File newFile=new File(System.currentTimeMillis()+" ");
System.out.println("newFile对象是否存在:"+newFile.exists());
//以指定newFile对象来创建一个文件
newFile.createNewFile();
//以newFile对象来创建一个目录,因为newFile已经存在
//所以下面方法返回false,即无法创建该目录
newFile.mkdir();
//使用list方法列出当前路径下的所有文件和路径
String[] fileList=file.list();
System.out.println("=====当前路径下所有文件和路径如下:=====");
for(String fileName:fileList)
{
System.out.println(fileName);
}
//以listRoots()静态方法列出所有的磁盘根路径
File[] roots=File.listRoots();
System.out.println("====系统所有根路径如下====");
for(File root:roots)
{
System.out.println(root);
}
}
}</span>
2.文件过滤器
<span style="font-family:Times New Roman;font-size:18px;">package com.filenamefilter.test;
import java.io.File;
public class FileNameFilter {
public static void main(String[] args) {
File file=new File(".");
String[] namelist=file.list();
for(String name:namelist)
{
//如果文件名以.txt结尾或者文件对应一个路径,则返回该文件
if(name.endsWith(".txt")||(new File(name).isDirectory()))
{
System.out.println(name);
}
}
}
}
</span>
3.字节流和字符流
<span style="font-family:Times New Roman;font-size:18px;">package com.stream.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class StreamTest {
public static void main(String[] args) throws IOException {
try(//创建字节输入流
FileInputStream fis=new FileInputStream(
"D:/JavaSets/IoTest/src/com/stream/test/"
+ "test.txt")){
//创建一个长度为1024的“竹筒”
byte[] bbuf=new byte[1024];
//用于保存实际读取的数据
int hasRead=0;
//使用循环重复取水的过程
while((hasRead=fis.read(bbuf))>0)
{
//取出竹筒中的水滴(字节),将字节数组转换成字符串输入
System.out.println(new String(bbuf,0,hasRead));
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
try(//创建字符输入流
FileReader fr=new FileReader(
"D:/JavaSets/IoTest/src/com/stream/test/"
+ "test.txt")){
//创建一个长度为32的“竹筒”
char[] bbuf=new char[32];
//用于保存实际读取的数据
int hasRead=0;
//使用循环重复取水的过程
while((hasRead=fr.read(bbuf))>0)
{
//取出竹筒中的水滴(字节),将字符数组转换成字符串输入
System.out.print(new String(bbuf,0,hasRead));
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
try(
//创建字节输入流
FileInputStream fis=new FileInputStream(
"D:/JavaSets/IoTest/src/com/stream/test/"
+ "test.txt");
//创建字节输出流
FileOutputStream fos=new FileOutputStream(""
+ "D:/JavaSets/IoTest/src/com/stream/test/"
+ "testcopy.txt");
){
byte[] buff=new byte[32];
int hasRead=0;
//循环从输入流中取出数据
while((hasRead=fis.read(buff))>0)
{
//每读取一次,即写入文件输出流,读了多少,就写多少
fos.write(buff,0,hasRead);
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
try(
FileWriter fw=new FileWriter("poem.txt");
){
fw.write("锦瑟\r\n");
fw.write("锦瑟无端五十弦,一弦一柱思华年。\r\n");
fw.write("庄生晓梦迷蝴蝶,望帝春心托杜鹃。\r\n");
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
</span>
4.处理流
<span style="font-family:Times New Roman;font-size:18px;">package com.io.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class IOtest {
public static void main(String[] args) throws FileNotFoundException, IOException {
try(
//创建节点流,节点流使用起来不方便
FileOutputStream fos=new FileOutputStream(""
+ "D:/JavaSets/IoTest/poem.txt");
//节点流包装秤过滤流
PrintStream ps=new PrintStream(fos);
)
{
//使用PrintStream执行输出
ps.println("普通字符串");
//直接使用PrintStream输出对象
ps.println(new IOtest());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
5.转换流
<span style="font-family:Times New Roman;font-size:18px;">package com.converstream.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ConvertStream {
public static void main(String[] args) throws IOException {
try(
//将System.in对象转换成Reader对象(字节流->字符流)
InputStreamReader reader=new InputStreamReader(System.in);
//将普通的Reader包装成BufferedReader
BufferedReader br=new BufferedReader(reader);
)
{
String line=null;
//采用循环方式逐行地读取
while((line=br.readLine())!=null)
{
//如果读取的字符串为"exit",则程序退出
if(line.equals("exit"))
{
System.exit(1);
}
//打印读取的内容
System.out.println("输入内容:"+line);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
6.字节流和字符流
<span style="font-family:Times New Roman;font-size:18px;">package com.stringnode.test;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
public class StringNodeTest {
public static void main(String[] args) throws IOException {
String src="从明天起做一个幸福的人\n"
+"喂马,劈柴,周游世界\n";
char[] buffer=new char[32];
int hasRead=0;
try(
StringReader sr=new StringReader(src);
)
{
//采用循环读取的方式读取字符串
while((hasRead=sr.read(buffer))>0)
{
System.out.println(new String(buffer,0,hasRead));
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
try(
//创建StringWriter时,实际上以一个StringBuffer作为输出节点
//下面指定的20就是StringBuffer的初始长度
StringWriter sw=new StringWriter();
)
{
//调用StringWriter的方法执行输出
sw.write("有个一美丽的新世界,\n");
sw.write("她在远方等我,\n");
System.out.println("---下面是sw字符串节点里面的内容---");
//使用toString()方法返回StringWriter字符串节点的内容
System.out.println(sw.toString());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
7.推回输入流
<span style="font-family:Times New Roman;font-size:18px;">package com.pushback.test;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PushbackReader;
public class PushbackTest {
public static void main(String[] args) throws FileNotFoundException, IOException {
try(
//创建一个pushbackreader对象,指定推回缓冲区的长度为64
PushbackReader pr=new PushbackReader(new FileReader
("D:/JavaSets/IoTest/src/com/pushback/test/PushbackTest.java"),64)
)
{
char[] buf=new char[32];
//用以保存上次读取的字符串内容
String lastContent="";
int hasRead=0;
//循环读取文件内容
while((hasRead=pr.read(buf))>0)
{
//将读取的内容转换成字符串
String content=new String(buf,0,hasRead);
int targetIndex=0;
//将上次读取的字符串和本次读取的字符串拼起来
//查看是否包含目标字符串,如果包含目标字符串
if((targetIndex=(lastContent+
content).indexOf("new PushbackReader"))>0)
{
//将本次内容和上次内容一起推回到缓冲区
pr.unread((lastContent+content).toCharArray());
//重新定义一个长度为targetIndex的char数组
if(targetIndex>32)
{
buf=new char[targetIndex];
}
//再次读取指定长度的内容
pr.read(buf,0,targetIndex);
//打印读取的内容
System.out.println(new String(buf,0,targetIndex));
System.exit(0);
}
else
{
//打印上次读取的内容
System.out.println(lastContent);
//将本次内容设为上次读取的内容
lastContent=content;
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
8.从定向标准输入、输出
<span style="font-family:Times New Roman;font-size:18px;">package com.redictio.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class RedictIO {
public static void main(String[] args) throws IOException {
// try(
// //一次性创建printstream输出流
// PrintStream ps=new PrintStream(new FileOutputStream("out.txt"))
// )
// {
// //将标准输出重定向到Ps输出流
// System.setOut(ps);
// //向标准输出输出一个字符串
// System.out.println("普通字符串");
// //向标准输出输出一个对象
// System.out.println(new RedictIO());
// }
// catch(IOException ex)
// {
// ex.printStackTrace();
// }
try(
FileInputStream fis=new FileInputStream(
"D:/JavaSets/IoTest/src/com/redictio/"
+ "test/RedictIO.java");
)
{
//将标准输入重定向到fis输入流
System.setIn(fis);
//使用system.in创建Scanner对象,用于获取标准输入
Scanner sc=new Scanner(System.in);
//增加下面一行只把回车作为分隔符
sc.useDelimiter("\n");
while(sc.hasNext())
{
//输出输入项
System.out.println("键盘输入的内容是:"+sc.next());
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
9.Java虚拟机读写其他进程的数据
<span style="font-family:Times New Roman;font-size:18px;">package com.process.test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Scanner;
public class ReadFromProcess {
public static void main(String[] args) throws IOException {
//运行javac命令,返回运行该命令的子进程
Process p=Runtime.getRuntime().exec("javac");
try(
//以p进程的错误流创建BufferedReader对象
//该错误流对本程序是输入流,对p进程则是输出流
BufferedReader br=new BufferedReader(
new InputStreamReader(p.getErrorStream()))
)
{
String buff=null;
//采取循环方式读取p进程的错误输出
while((buff=br.readLine())!=null)
{
System.out.println(buff);
}
}
//运行java ReadStandard命令,返回该命令的子进程
Process p=Runtime.getRuntime().exec("java ReadStandard");
try(
//以p进程的输出流来创建PrintStream对象
//这个输出流对本程序是输出流,对P进程则是输入流
PrintStream ps=new PrintStream(p.getOutputStream());
)
{
//向ReadStandard程序写入内容,这些内容将被ReadStandard读取
ps.println("普通字符串");
ps.println(new ReadFromProcess());
}
ReadStandard ss=new ReadStandard();
}
}
//定义一个ReadStandard类,该类可以接受标准输入,并将标准输入写入outone.txt
class ReadStandard{
public static void main(String[] args) throws FileNotFoundException
{
try(
//使用System.in创建Scanner对象,用于获取标准输入
Scanner sc=new Scanner(System.in);
PrintStream ps=new PrintStream(
new FileOutputStream("D:/JavaSets/IoTest/poem.txt"))
)
{
//增加下面一行就是把回车作为分隔符
sc.useDelimiter("\n");
//判断是否还有下一个输入项
while(sc.hasNext())
{
//输出输入项
ps.println("键盘输入的内容:"+sc.next());
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
10.RandomAccessFile
<span style="font-family:Times New Roman;font-size:18px;">package com.randomaccessfile.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFIle {
public static void insert(String fileName,
long pos,String insertContent) throws IOException{
File tmp=File.createTempFile("tmp", null);
tmp.deleteOnExit();
try(
RandomAccessFile raf=new RandomAccessFile(fileName,"rw");
//使用临时文件来保存插入点后的数据
FileOutputStream tmpOut=new FileOutputStream(tmp);
FileInputStream tmpIn=new FileInputStream(tmp);
)
{
//将记录指针移到指定位置
raf.seek(pos);
//下面将插入点后的内容读入临时文件中保存
byte[] bbuf=new byte[64];
//用于保存实际读取的字节数
int hasRead=0;
//循环读取插入点后的数据
while((hasRead=raf.read(bbuf))>0)
{
//将读取的数据写入临时文件
tmpOut.write(bbuf,0,hasRead);
}
//下面代码用于插入内容
//把文件记录指针重新定位到pos位置
raf.seek(pos);
//追加需要插入的内容
raf.write(insertContent.getBytes());
//追加临时文件中的内容
while((hasRead=tmpIn.read(bbuf))>0)
{
raf.write(bbuf,0,hasRead);
}
}
}
public static void main(String[] args) throws IOException {
insert("D:/JavaSets/IoTest/poem.txt",22,"**此处为要插入的内容!**\r\n");
}
}
</span>
12.对象序列化
<span style="font-family:Times New Roman;font-size:18px;">package com.serialize.test;
public class Person
implements java.io.Serializable{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}</span>
<span style="font-family:Times New Roman;font-size:18px;">package com.serialize.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Serialize {
public static void main(String[] args) throws
FileNotFoundException, IOException, ClassNotFoundException {
try(
//创建一个ObjectOutputStream输出流
ObjectOutputStream oos=new ObjectOutputStream(
new FileOutputStream("object.txt"))
)
{
Person per=new Person("孙悟空",66);
//将per对象写入输出流
oos.writeObject(per);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
try(
//创建一个ObjectInputStream输入流
ObjectInputStream ois=new ObjectInputStream(
new FileInputStream("object.txt"));
)
{
//从输入流中读取一个java对象,并将其强制转换类型为Person类
Person p=(Person)ois.readObject();
System.out.println("名字为:"+p.getName()+"\n年龄为:"+p.getAge());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
<span style="font-family:Times New Roman;font-size:18px;">package com.serialize.test;
public class Teacher
implements java.io.Serializable{
private String name;
private Person student;
public Teacher(String name,Person student)
{
this.name=name;
this.student=student;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getStudent() {
return student;
}
public void setStudent(Person student) {
this.student = student;
}
}
</span>
<span style="font-family:Times New Roman;font-size:18px;">package com.serialize.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Teachertest {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
try(
//创建一个ObjectOutputStream输出流
ObjectOutputStream oos=new ObjectOutputStream(
new FileOutputStream("teacher.txt"))
)
{
Person per=new Person("李明",500);
Teacher t1=new Teacher("张三",per);
Teacher t2=new Teacher("李四",per);
//依次将4个对象写入输出流
oos.writeObject(t1);
oos.writeObject(t2);
oos.writeObject(per);
oos.writeObject(t2);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
//读取序列化文件
try(
//创建一个ObjectInputStream输入流
ObjectInputStream ois=new ObjectInputStream(
new FileInputStream("teacher.txt"));
)
{
//依次读取ObjectInputStream输入流中的4个对象
Teacher t1=(Teacher)ois.readObject();
Teacher t2=(Teacher)ois.readObject();
Person p=(Person)ois.readObject();
Teacher t3=(Teacher)ois.readObject();
//输出true
System.out.println("t1的student引用和p是否相同:"+
(t1.getStudent()==p));
//输出true
System.out.println("t2的student引用和p是否相同:"+
(t2.getStudent()==p));
//输出true
System.out.println("t2和t3是否是同一个对象:"+
(t2==t3));
System.out.println("p名字为:"+p.getName()+"p年龄为:"+p.getAge());
System.out.println("t1名字为:"+t1.getName()+"t1年龄为:"+t1.getStudent().getAge());
System.out.println("t2名字为:"+t2.getName()+"t2年龄为:"+t2.getStudent().getAge());
System.out.println("t3名字为:"+t3.getName()+"t3年龄为:"+t3.getStudent().getAge());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
13.自定义序列化
<span style="font-family:Times New Roman;font-size:18px;">package com.transitent.test;
import java.io.Serializable;
public class Person
implements Serializable{
private String name;
private transient int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
</span>
<span style="font-family:Times New Roman;font-size:18px;">package com.transitent.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TransientTest {
public static void main(String[] args)
throws FileNotFoundException, IOException, ClassNotFoundException {
try(
//创建一个ObjectOutputStream输出流
ObjectOutputStream oos=new ObjectOutputStream(
new FileOutputStream("transient.txt"));
//创建一个ObjectInputStream输入流
ObjectInputStream ois=new ObjectInputStream(
new FileInputStream("transient.txt"));
)
{
Person per=new Person("李四",45);
//系统将per对象转换成字节序列并输出
oos.writeObject(per);
Person p=(Person)ois.readObject();
System.out.println(p.getAge());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
<span style="font-family:Times New Roman;font-size:18px;">package com.customserializable.test;
import java.io.IOException;
import java.util.ArrayList;
public class Person
implements java.io.Serializable{
private String name;
private int age;
public Person(String name, int age) {
System.out.println("有参数的构造器!");
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/*
* 下面两个方法提供给系统调用,系统会调用该方法完成实际的序列化
*/
// private void writeObject(java.io.ObjectOutputStream out)
// throws IOException
// {
// //将name实例变量值反转后写入二进制流,先将name进行反转,自然也可以做更复杂的加密
// out.writeObject(new StringBuffer(name).reverse());
// out.writeInt(age);
// }
// private void readObject(java.io.ObjectInputStream in)
// throws ClassNotFoundException, IOException
// {
// //将读取的字符串反转后赋给name实例变量,而且恢复的顺序要与之前写入的顺序一致
// this.name=((StringBuffer)in.readObject()).reverse().toString();
// this.age=in.readInt();
// }
//重写writeReplace方法,程序在序列化该对象之前,先调用该方法
private Object writeReplace ()
{
ArrayList<Object> list=new ArrayList<Object>();
list.add(name);
list.add(age);
return list;
}
}
</span>
<span style="font-family:Times New Roman;font-size:18px;">package com.customserializable.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class replace {
public static void main(String[] args)
throws FileNotFoundException, IOException, ClassNotFoundException {
try(
//创建一个ObjectOutputStream输出流
ObjectOutputStream oos=new ObjectOutputStream(
new FileOutputStream("replace.txt"));
//创建一个ObjectInputStream输入流
ObjectInputStream ois=new ObjectInputStream(
new FileInputStream("replace.txt"));
)
{
Person per=new Person("王五",34);
//系统将per对象转换成字节序列并输出
oos.writeObject(per);
// Person p=(Person)ois.readObject();
ArrayList list=(ArrayList)ois.readObject();
System.out.println(list);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
</span>
14.使用Buffer
package com.nio.test;
import java.nio.CharBuffer;
public class BufferTest {
public static void main(String[] args) {
//创建Buffer
CharBuffer buff=CharBuffer.allocate(8);
System.out.println("capacity:"+buff.capacity());
System.out.println("limit:"+buff.limit());
System.out.println("position:"+buff.position());
//放入元素
buff.put('a');
buff.put('b');
buff.put('c');
System.out.println("加入三个元素后:position="+buff.position());
//调用flip()方法
buff.flip();
System.out.println("执行flip()后,limit="+buff.limit());
System.out.println("执行flip()后,position="+buff.position());
//取出第一个元素
System.out.println("第一个元素(position=0):"+buff.get());
System.out.println("取出第一个元素后:position="+buff.position());
//调用clear()方法
buff.clear();
System.out.println("执行clear()后,limit="+buff.limit());
System.out.println("执行clear()后,position="+buff.position());
System.out.println("执行clear()后,缓冲区内容并没有被清除:第三个元素为:"
+ buff.get(2));
System.out.println("执行绝对读取后,position="+buff.position());
}
}
15.使用Channel
package com.nio.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
public class FileChannelTest {
public static void main(String[] args) throws FileNotFoundException, IOException {
File f=new File
("D:/JavaSets/IoTest/src/com/nio/test/FileChannelTest.java");
try(
//创建FileInputStream,以该文件输入流创建FileChannel
FileChannel inChannel=new
FileInputStream(f).getChannel();
//以文件输出流创建FileChannel,用以控制输出
FileChannel outChannel=new
FileOutputStream("a.txt").getChannel();
)
{
//将FileChannel里的全部数据映射成ByteBuffer
MappedByteBuffer buffer=inChannel.map(
FileChannel.MapMode.READ_ONLY, 0, f.length());
//使用GBK的字符集来创建解码器
Charset charset=Charset.forName("GBK");
//直接将buffer里的数据全部输出
outChannel.write(buffer);
//再次调用buffer的clear()方法,复原limit,position的位置
buffer.clear();
//创建解码器(CharsetDecoder)对象
CharsetDecoder decoder=charset.newDecoder();
//使用解码器将ByteBuffer转换成charBuffer
CharBuffer charbuffer=decoder.decode(buffer);
//CharBuffer的toString方法可以获取对应的字符串
System.out.println(charbuffer);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
16.使用RandomFileChannelpackage com.nio.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
public class RandomFileChannelTest {
public static void main(String[] args) throws FileNotFoundException, IOException {
File f=new File("D:/JavaSets/IoTest/poem.txt");
try(
//创建一个RandomAccessFile对象
RandomAccessFile raf=new RandomAccessFile(f,"rw");
//获取RandomAccessFile对应的Channel
FileChannel randomChannel=raf.getChannel();
)
{
//将Channel中的所有数据映射成ByteBuffer
ByteBuffer buffer=randomChannel.map
(FileChannel.MapMode.READ_ONLY, 0, f.length());
//把Channel的记录指针移动到最后
randomChannel.position(f.length());
//将buffer中的所有数据输出
randomChannel.write(buffer);
}
try(
//创建文件输入流
FileInputStream fis=new FileInputStream
("D:/JavaSets/IoTest/poem.txt");
//创建一个FileChannel
FileChannel fcin=fis.getChannel();
)
{
//定义一个ByteBuffer对象,用于重复取水
ByteBuffer bbuf=ByteBuffer.allocate(256);
//将FileChannel中的数据写入ByteBuffer中
while(fcin.read(bbuf)!=-1)
{
//锁定Buffer的空白区
bbuf.flip();
//创建Charset对象
Charset charset=Charset.forName("GBK");
//创建解码器(CharsetDecoder)对象
CharsetDecoder decoder=charset.newDecoder();
//将ByteBuffer的内容转码
CharBuffer cbuff=decoder.decode(bbuf);
System.out.println(cbuff);
//将Buffer初始化,为下一次读取数据做准备
bbuf.clear();
}
}
}
}
17.字符集和Charset
package com.nio.test;
import java.nio.charset.Charset;
import java.util.SortedMap;
public class CharsetTest {
public static void main(String[] args) {
//获取Java支持的全部字符集
SortedMap<String,Charset> map=Charset.availableCharsets();
for(String alias:map.keySet())
{
//输出字符集的别名和对应的Charset对象
System.out.println(alias+"----->"+map.get(alias));
}
}
}
package com.nio.test;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class CharsetTransform {
public static void main(String[] args) throws CharacterCodingException {
//创建简体中文对应的charset
Charset cn=Charset.forName("GBK");
//获取cn对象对应的编码器和解码器
CharsetEncoder cnEncoder=cn.newEncoder();
CharsetDecoder cnDecoder=cn.newDecoder();
//创建一个CharBuffer对象
CharBuffer cbuff=CharBuffer.allocate(8);
cbuff.put('孙');
cbuff.put('悟');
cbuff.put('空');
cbuff.flip();
//将CharBuffer中的字符序列转换成字节序列
ByteBuffer bbuff=cnEncoder.encode(cbuff);
//循环访问ByteBuffer中的每个字节
for(int i=0;i<bbuff.capacity();i++)
{
System.out.println(bbuff.get(i)+" ");
}
//将ByteBuffer的数据解码成字符序列
System.out.println("\n"+cnDecoder.decode(bbuff));
}
}
18文件锁
package com.nio.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLockTest {
public static void main(String[] args)
throws FileNotFoundException, IOException, InterruptedException {
try(
//使用FileOutputStream获取FileChannel
FileChannel channel=new
FileOutputStream("a.txt").getChannel();
)
{
//使用非阻塞方式对指定文件加锁
FileLock lock=channel.tryLock();
//程序暂停10s
Thread.sleep(10000);
lock.release();
}
}
}
19.Java7的NIO.2
package com.nio2.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributeView;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class NIOTest {
public static void main(String[] args)
throws FileNotFoundException, IOException, InterruptedException {
//以当前路径来创建Path对象
Path path=Paths.get(".");
System.out.println("path里面包含的路径数量:"+path.getNameCount());
//获取path对应的绝对路径
Path absolutePath=path.toAbsolutePath();
System.out.println(absolutePath);
//获取绝对路径的根路径
System.out.println("absolutePath的根路径:"+absolutePath.getRoot());
//获取绝对路径所包含的路径数量
System.out.println("absolutePath里包含的路径数量:"+
absolutePath.getNameCount());
System.out.println(absolutePath.getName(2));
//以多个String来构建Path对象
Path path2=Paths.get("g:"+"publish"+"codes");
System.out.println(path2);
/*
* Files是一个操作文件的工具类,提供大量便捷的工具方法
*/
Files.copy(Paths.get("D:/JavaSets/IoTest/poem.txt"),
new FileOutputStream("f.txt"));
//判断poem.txt文件是否为隐藏文件
System.out.println("poem是否为隐藏文件:"+
Files.isHidden(Paths.get("D:/JavaSets/IoTest/poem.txt")));
//一次性读取poem的文件的所有行
List<String> lines=Files.readAllLines(Paths.get
("D:/JavaSets/IoTest/poem.txt"), Charset.forName("gbk"));
System.out.println(lines);
System.out.println("poem文件的大小为:"+
Files.size(Paths.get("D:/JavaSets/IoTest/poem.txt")));
List<String> poemc=new ArrayList<>();
poemc.add("水晶潭底银鱼跃");
poemc.add("清徐风中碧竿横");
//直接将多个字符串内容写入指定文件
Files.write(Paths.get("D:/JavaSets/IoTest/poemc.txt"),
poemc, Charset.forName("gbk"));
//判断C盘的总空间,可用空间
System.out.println("C共有空间:"+
(Files.getFileStore(Paths.get("C:"))).getTotalSpace());
System.out.println("C可用空间:"+
(Files.getFileStore(Paths.get("C:"))).getUsableSpace());
/*
* 使用FileVistor遍历文件和目录
*/
Files.walkFileTree(Paths.get("D:","JavaSets","IoTest"),
new SimpleFileVisitor<Path>()
{
//访问文件时触发该方法
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs)
{
System.out.println("正在访问:"+file+"文件");
//NIOTest.java
if(file.endsWith("NIOTest.java"))
{
System.out.println("---已经找到目标文件---");
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
//开始访问目录事触发该方法
public FileVisitResult preVisitDirectory
(Path dir,BasicFileAttributes attrs)
{
System.out.println("正在访问:"+dir+"路径");
return FileVisitResult.CONTINUE;
}
});
/*
* 使用WatchService监控文件变化
*/
//获取文件系统的WatchService对象
WatchService wathcservice=FileSystems.getDefault()
.newWatchService();
//为D盘注册监听
Paths.get("D:/").register(wathcservice,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
while(true)
{
//获取下一个文件变化事件
WatchKey key=wathcservice.take();
for(WatchEvent<?> event:key.pollEvents())
{
System.out.println(event.context()+"文件发生了"+
event.kind()+"事件!");
}
//重设WatchKey
boolean valid=key.reset();
//如果重设失败,退出监听
if(!valid)
{
break;
}
}
/*
* 访问文件属性
*/
//获取将要操作额文件
Path testpath=Paths.get(
"D:/JavaSets/IoTest/src/com/nio2/test/NIOTest.java");
//获取访问基本属性的BasicFileAttributeView
BasicFileAttributeView basicView=Files.getFileAttributeView(
testpath, BasicFileAttributeView.class);
//获取访问基本属性的BasicFileAttributes
BasicFileAttributes basicAttributes=basicView.readAttributes();
//访问文件的基本属性
System.out.println("创建时间:"+
new Date(basicAttributes.creationTime().toMillis()));
System.out.println("最后访问时间"+
basicAttributes.lastAccessTime().toMillis());
System.out.println("最后修改时间"+
basicAttributes.lastModifiedTime().toMillis());
System.out.println("文件大小:"+basicAttributes.size());
//获取访问文件属主信息的FileOwnerAttributeView
FileOwnerAttributeView ownerView=Files.getFileAttributeView(
testpath, FileOwnerAttributeView.class);
//获取该文件所属的用户
System.out.println(ownerView.getOwner());
//获取系统中guest对应的用户
UserPrincipal user=FileSystems.getDefault()
.getUserPrincipalLookupService()
.lookupPrincipalByName("guest");
//修改用户
ownerView.setOwner(user);
//获取访问自定义属性的FileOwnerAttributeView
UserDefinedFileAttributeView userView=Files.getFileAttributeView(
testpath,UserDefinedFileAttributeView.class);
List<String> attrNames=userView.list();
//遍历所有的自定义属性
for(String name:attrNames)
{
ByteBuffer buf=ByteBuffer.allocate(userView.size(name));
userView.read(name, buf);
buf.flip();
String value=Charset.defaultCharset().decode(buf).toString();
System.out.println(name+"--->"+value);
}
//添加一个自定义属性
userView.write("发行者", Charset.defaultCharset()
.encode("Crazy Java"));
//获取访问Dos属性的DosFileAttributeView
DosFileAttributeView dosView=Files.getFileAttributeView(
testpath, DosFileAttributeView.class);
//将文件设置隐藏,只读
dosView.setHidden(true);
dosView.setReadOnly(true);
}
}