Java IO简单测试编码
File类:
构造方法一:(最常用)
package com.io;
import java.io.File;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args) throws IOException
{
//指定好这个文件的路径和名称,但是并没有创建它
File file = new File("D:\\test.txt");
//java io包里面的所有类几乎都会抛出IoException
System.out.println(file.createNewFile());
}
}
构造方法二:
package com.io;
import java.io.File;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args) throws IOException
{
//声明D:/abc这个目录,其实这个目录已经存在
File file1 = new File("D:/abc");
File file2 = new File(file1, "text.txt");
file2.createNewFile();
}
}
构造方法三:
package com.io;
import java.io.File;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args) throws IOException
{
File file = new File("D:/abc", "world.txt");
file.createNewFile();
}
}
创建一个目录:
package com.io;
import java.io.File;
public class FileTest2
{
public static void main(String[] args)
{
//D:/abc/xyz是已经存在的目录,mkdir()创建的是hello这个目录
//并且只能创建hello这个目录,若xyz不存在,则创建不成功
File file = new File("D:/abc/xyz/hello");
file.mkdir();
}
}
创建多层目录:
package com.io;
import java.io.File;
public class FileTest2
{
public static void main(String[] args)
{
//D:/abc/xyz/hello这些目录都不存在,mkdirs可以全部递归的创建
File file = new File("D:/abc/xyz/hello");
file.mkdirs();
System.out.println(file.isDirectory());
}
}
检查创建的File是文件还是目录:
package com.io;
import java.io.File;
public class FileTest2
{
public static void main(String[] args)
{
//D:/abc/xyz/hello这些目录都不存在,mkdirs可以全部递归的创建
File file = new File("D:/abc/xyz/hello");
file.mkdirs();
System.out.println(file.mkdirs());
System.out.println(file.isDirectory());
System.out.println(file.isFile());
}
}
List方法:打印出一个目录下的所有文件和目录(目录里的内容不会打印):
package com.io;
import java.io.File;
public class FileTest2
{
public static void main(String[] args)
{
File file = new File("G:/eclipse");
String[] names = file.list();
for(String str : names)
{
System.out.println(str);
}
}
}
运行结果:仅限于本人电脑
.eclipseproduct
artifacts.xml
configuration
dropins
eclipse.exe
eclipse.ini
eclipsec.exe
epl-v10.html
features
notice.html
p2
plugins
readme
功能一样的listFiles方法:
package com.io;
import java.io.File;
public class FileTest2
{
public static void main(String[] args)
{
File file = new File("G:/eclipse");
File[] fs = file.listFiles();
for(File f : fs)
{
System.out.println(f.getName());
}
}
}
运行结果是一样的
Exit(),getName(),getParent()方法的使用:
package com.io;
import java.io.File;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args) throws IOException
{
File file = new File("D:/abc/xyz"); //指定一个路径名
System.out.println(file.exists());//判断这个路径名目录或文件是否存在
System.out.println(file.getName());
System.out.println(file.getParent());
}
}
搜索一个文件夹里的.java文件
方法一:
package com.io;
import java.io.File;
public class FileTest3
{
public static void main(String[] args)
{
File file = new File("D:\\abc\\xyz");
String[] names = file.list();
for(String name : names)
{
if(name.endsWith(".java"))
{
System.out.println(name);
}
}
}
}
方法二:
用到匿名内部类
package com.io;
import java.io.File;
import java.io.FilenameFilter;
public class FileTest
{
public static void main(String[] args)
{
File file = new File("D:\\abc\\xyz");
String[] names = file.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
if(name.endsWith(".java"))
{
return true;
}
else
return false;
}
});
for(String name : names)
{
System.out.println(name);
}
}
}
递归删除文件的代码:
package org.wiksys;
import java.io.File;
public class FileDeleteUsingRecursion {
/**
* @author wiksys
* @param args
*/
public static void main(String[] args) {
}
public static void deleteAll(File file){
if(file.isFile() || file.list().length == 0){
file.delete();
}
else{
File[] files=file.listFiles();
for (File f : files) {
deleteAll(f);
f.delete();
}
}
}
}
流(Stream):
从硬盘中读取文件:
InputStream
package com.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class InputText
{
public static void main(String[] args) throws Exception
{
InputStream is = new FileInputStream("D:/abc/linux.txt");
byte[] buffer = new byte[200];
int length;
while(-1 != (length = is.read(buffer, 0, 200)))
{
String str = new String(buffer, 0, length);
System.out.println(str);
}
is.close();
}
}
输出到外设的文件的输出流:
OutPutStream
package com.io;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class OutPutStream
{
public static void main(String[] args) throws Exception
{
OutputStream fos = new FileOutputStream("D:\\xyz\\abc.txt", true);
String str = "Welcome";
byte[] buffer = str.getBytes();
fos.write(buffer);
fos.close();
}
}
过滤流
缓冲过滤流:
package com.io;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class BufferedOutStreamTest
{
public static void main(String[] args) throws Exception
{
OutputStream os = new FileOutputStream("1.txt");
BufferedOutputStream bos = new BufferedOutputStream(os);
bos.write("http://google.com.hk".getBytes());
bos.close();
}
}
字节流:
存入变量的值和变量的类型信息到文件里去,即读取这个文件的内容就可以知道该文件是属于什么类型的变量。
package org.wiksys;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class DeleteStream
{
public static void main(String[] args) throws Exception
{
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream("data.txt")));
byte b = 3;
int i = 12;
char ch = 'a';
float f = 3.3f;
dos.writeByte(b);
dos.writeInt(i);
dos.writeChar(ch);
dos.writeFloat(f);
dos.close();
DataInputStream dis = new DataInputStream(new BufferedInputStream(
new FileInputStream("data.txt")));
//读和写的顺序要保持一致
System.out.println(dis.readByte());
System.out.println(dis.readInt());
System.out.println(dis.readChar());
System.out.println(dis.readFloat());
dis.close();
}
}
运行结果是一个二进制文件的乱码。
字符流:
加入了Reader Writer两个抽象类,相当于字节流中的InputStream和OutputStream,由于是抽象类所以要用他们的子类来完成实际的工作。
实例:
package com.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class StreamTest
{
public static void main(String[] args) throws IOException
{
FileOutputStream fos = new FileOutputStream("D:\\xyz\\abc.txt", true);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("http://www.google.com");
bw.write("\n");
bw.write("http://www.baidu.com");
bw.close();
FileInputStream fis = new FileInputStream("D:\\xyz\\abc.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
while(null != str)
{
System.out.println(str);
str = br.readLine();
}
br.close();
}
}
标准输入输出
package com.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Standardin
{
public static void main(String[] args) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(isr);
String str;
while(null != (str = bis.readLine()))
{
System.out.println(str);
}
}
}
从文件中读取然后输出到控制台上:
FileReader从文件中读取信息
package com.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReader1
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("C:\\Users\\XiaoKang\\Desktop\\memo\\abc.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while(null != (str = br.readLine()))
{
System.out.println(str);
}
br.close();
}
}
注意一定要关闭流,这样才能将数据从缓冲区输出到文件上面去,这一点一定要注意。
FilerWriter文件从内存中相外设写文件:
向文件中写字符,而不是字节流
package com.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FilerWriter1
{
public static void main(String[] args) throws IOException
{
String str = "Welcome to Dalian";
char[] ch = new char[str.length()];
str.getChars(0, str.length(), ch, 0);
FileWriter fw = new FileWriter("C:\\Users\\XiaoKang\\Desktop\\memo\\abc.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(ch);
bw.close();
}
}
CharArrayReader(从字符数组里面读):
字符数组不同与字符串。
package com.io;
import java.io.CharArrayReader;
import java.io.IOException;
public class CharArrayReader1
{
public static void main(String[] args) throws IOException
{
String str = "hello world";
char[] ch = new char[str.length()];
str.getChars(0, str.length(), ch, 0);
CharArrayReader car = new CharArrayReader(ch);
int i;
while(-1 != (i = car.read()))
{
System.out.print((char)i);
}
}
}
查看本机使用的字符集
返回当前系统中所有可用的字符集:
package com.io;
import java.util.Properties;
public class Charset
{
public static void main(String[] args)
{
Properties p = System.getProperties();
p.list(System.out);
}
}
局部运行结果:
java.vm.specification.vendor=Oracle Corporation
user.variant=
os.name=Windows 7
sun.jnu.encoding=GBK
java.library.path=C:\Program Files\Java\jre7\bin;C:\Win...
java.specification.name=Java Platform API Specification
java.class.version=51.0
sun.management.compiler=HotSpot Client Compiler
os.version=6.1
可以看出本机的文件编码方式是GBK的,GBK是GB2312的扩展版本,是中文的字符编码集。
RandomAccessFile(随机访问文件类)
它包装了一个随机访问的文件。他不是派生于InputStream和OutputStream,而是实现定义了基本输入/输入方法的DataInput和DataOutput接口。它支持定位请求----也就是说,可以在文件内部放置文件指针。他有两个构造方法。
因为他实现了两个类,所以它即能读又能写,实例如下:
package com.io;
import java.io.RandomAccessFile;
public class RandomAccessFile1
{
public static void main(String[] args) throws Exception
{
Person p1 = new Person(1001, "zhangsan", 172.02);
RandomAccessFile raf = new RandomAccessFile("D:\\abc\\xyz.txt", "rw");
p1.write(raf);
Person p2 = new Person();
raf.seek(0);
p2.read(raf);
System.out.println(p2.getId() + "," + p2.getName() + "," + p2.getHeight());
}
}
class Person
{
int id;
String name;
double height;
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public double getHeight()
{
return height;
}
public Person()
{
}
public Person(int id, String name, double height)
{
this.id = id;
this.name = name;
this.height = height;
}
public void write(RandomAccessFile raf) throws Exception
{
raf.writeInt(this.id);
raf.writeUTF(this.name);
raf.writeDouble(this.height);
}
public void read(RandomAccessFile raf) throws Exception
{
this.id = raf.readInt();
this.name = raf.readUTF();
this.height = raf.readDouble();
}
}
查看系统所包含的字符编码集:
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedMap;
public class CharSetTest
{
public static void main(String[] args)
{
SortedMap<String, Charset> map = Charset.availableCharsets();
Set<String> set = map.keySet();
for(Iterator<String> itr = set.iterator(); itr.hasNext();)
{
System.out.println(itr.next());
}
}
}
运行结果:
Big5
Big5-HKSCS
EUC-JP
EUC-KR
GB18030
GB2312
GBK
IBM-Thai
IBM00858
IBM01140
IBM01141
IBM01142
IBM01143
IBM01144
IBM01145
IBM01146
IBM01147
IBM01148
IBM01149
IBM037
IBM1026
•••
序列化
将对象转换为字节流保存起来,并在以后还原这个对象,这种机制叫做对象序列化(Serializable)
一个类如果想被序列化,则需要实现Java.io.Serializable接口,该类中没有定义任何方法,是一个标识性的接口(MarkerInterface)当一个类实现这个接口,就表示这个类的对象是可以序列化的。
序列化时,Static变量是无法序列化的;如果A包含了B的引用,那么A序列化的时候会将B也一并序列化;如果A可以序列化,B无法序列化,那么当序列化A的时候就会发生异常,这时候需要将B的引用设为transient,该关键字表示变量不会被序列化。
实例:
package com.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializableTest1
{
public static void main(String[] args) throws IOException, Exception
{
Child c1 = new Child(20, "zhangsan", 4.55);
Child c2 = new Child(50, "lisi", 4.67);
Child c3 = new Child(10, "wangwu", 17.18);
FileOutputStream fos = new FileOutputStream("D:\\xyz\\abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(c1);
oos.writeObject(c2);
oos.writeObject(c3);
oos.close();
System.out.println("--------------------");
FileInputStream fis = new FileInputStream("D:\\xyz\\abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Child c = null;
for(int i = 0; i < 3; i++)
{
c = (Child)ois.readObject();
System.out.println(c.age + "," + c.name + "," + c.height);
}
ois.close();
}
}
class Child implements Serializable
{
int age;
transient String name;
double height;
public Child(int age, String name, double height)
{
this.age = age;
this.name = name;
this.height = height;
}
}
运行结果:
--------------------
20,null,4.55
50,null,4.67
10,null,17.18
当我们在一个待序列化/反序列化的类中实现了一下(红色标记)两个private方法(方法声明要与上面保持一致)那么就允许我们以更加底层、更加细粒度的方式控制序列化和反序列化的过程。
package org.wiksys;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializableTest2
{
public static void main(String[] args) throws Exception
{
Person2 p1 = new Person2(20, "zhangsan", 4.55);
Person2 p2 = new Person2(50, "lisi", 4.67);
Person2 p3 = new Person2(10, "wangwu", 17.78);
FileOutputStream fos = new FileOutputStream("Person2.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(p3);
oos.close();
System.out.println("--------------------");
FileInputStream fis = new FileInputStream("Person2.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person2 p = null;
for (int i = 0; i < 3; i++)
{
p = (Person2) ois.readObject();
System.out.println(p.age + "," + p.name + "," + p.height);
}
ois.close();
}
}
class Person2 implements Serializable
{
int age;
String name;
double height;
public Person2(int age, String name, double height)
{
this.age = age;
this.name = name;
this.height = height;
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException
{
out.writeInt(age);
out.writeUTF(name);
System.out.println("write object");
}
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException
{
age = in.readInt();
name = in.readUTF();
System.out.println("read object");
}
}
以上就是Java IO的基础知识!
感谢大家支持!