IO流-------file类
在java中stream代表一种数据流(源),javaio的底层数据元
InputStream对象能产生数据流,就可以将数据取出,通用方法read()方法
OutputStream对象能接收数据流,就可以将数据写入,通用方法write()方法
在Inputstream和OutputStream数据源的基础上,从实际需要触发,重新封装不同的,各种各样的数据流
流-------文件对象
创建一个新文件
import java.io.*;
class Hello {
public static void main(String[] args) {
File f = new File("D:\\hello.txt");
try{
f.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}
File类的两个常量 这两个常量是什么作用呢, 路径分隔符,系统默认分隔符
import java.io.*;
class Hello {
public static void main(String[] args) {
System.out.println(File.separator);
System.out.println(File.pathSeparator);
}
}
用了之后有啥作用呢???
import java.io.*;
class Hello {
public static void main(String[] args) {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
try{
f.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}
删除一个文件
import java.io.*;
class Hello {
public static void main(String[] args) {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
if(f.exists()) {
f.delete();
}else {
System.out.println("文件不存在");
}
}
}
创建一个文件夹hello
import java.io.*;
class Hello {
public static void main(String[] args) {
String fileName = "D:"+File.separator+"hello";
File f = new File(fileName);
f.mkdir();
//f.delete(); 删除文件
}
}
列出某文件夹下的文件目录,包括隐藏文件
import java.io.*;
class Hello {
public static void main(String[] args) {
String fileName = "D:"+File.separator;
File f = new File(fileName);
String[] str = f.list();
for(int i=0;i<str.length;i++) {
System.out.println(str[i]);
}
}
}
输出的是完整的路径
import java.io.*;
class Hello {
public static void main(String[] args) {
String fileName = "D:"+File.separator;
File f = new File(fileName);
File[] str = f.listFiles(); //输出完整路径
for(int i=0;i<str.length;i++) {
System.out.println(str[i]);
}
}
}
判断一个指定的路径是否为文件夹
import java.io.*;
class Hello {
public static void main(String[] args) {
String fileName = "D:"+File.separator;
File f = new File(fileName);
if(f.isDirectory()) {
System.out.println("yes");
}else{
System.out.println("no");
}
}
}
文件复制
文件内容的复制
文件内相关内容的复制
文件内指定位置添加内容
搜索指定目录的全部内容
import java.io.*;
class Hello {
public static void main(String[] args) {
String fileName = "D:"+File.separator;
File f = new File(fileName);
print(f);
}
public static void print(File f) {
if(f != null) {
if(f.isDirectory()) {
File[] fileArray = f.listFiles();
if(fileArray != null) {
for(int i=0;i<fileArray.length;i++) {
print(fileArray[i]); //递归调用
}
}
}
else{
System.out.println(f);
}
}
}
}
使用RandomAccessFile写入文件
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
RandomAccessFile demo = new RandomAccessFile(f,"rw");
demo.writeBytes("hfdkkk");
demo.writeInt(23);
demo.writeBoolean(true);
demo.writeChar('A');
demo.writeFloat(1.21f);
demo .writeDouble(12.123);
demo.close();
}
}
内容显示是乱码,如何更改编码问题
字节流---向文件中写入字符串
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
OutputStream out = new FileOutputStream(f);
String str = "你好";
byte[] b = str.getBytes();
out.write(b);
out.close();
}
}
向文件中一个字节一个字节的写入字符串,为什么要一个一个的写入呢?
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
OutputStream out = new FileOutputStream(f);
String str = "你好";
byte[] b = str.getBytes();
for(int i=0;i<b.length;i++) {
out.write(b[i]);
}
out.close();
}
}
向文件中追加新的内容
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
OutputStream out = new FileOutputStream(f,true);//这是文件已经存在的意思
String str = "你好88888啊啊啊啊";
//String str = "\r\nRollen"; //可以换行
byte[] b = str.getBytes();
for(int i=0;i<b.length;i++) {
out.write(b[i]);
}
out.close();
}
}
读取文件内容
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
InputStream in = new FileInputStream(f);
byte[] b = new byte[1024];
in.read(b);
in.close();
System.out.println(new String(b)); //这里若是没有new String的话看到的是编码地
}
}
读取文件内指定的内容
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
InputStream in = new FileInputStream(f);
byte[] b = new byte[1024];
int len = in.read(b);
in.close();
System.out.println("读取长度为:"+len);
System.out.println(new String(b,0,len)); //这里若是没有new String的话看到的是编码地址
}
}
读取文件内指定的内容,节省空间
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
InputStream in = new FileInputStream(f);
byte[] b = new byte[(int)f.length()];
in.read(b);
System.out.println("读取长度为:"+f.length());
in.close();
System.out.println(new String(b)); //这里若是没有new String的话看到的是编码地
}
}
读取文件内指定的内容,一个一个的读取
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
InputStream in = new FileInputStream(f);
byte[] b = new byte[(int)f.length()];
for(int i=0;i<b.length;i++){
b[i] = (byte)in.read(b);
}
in.close();
System.out.println(new String(b)); //这里若是没有new String的话看到的是编码地址
}
}
读取整个文件内容
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
InputStream in = new FileInputStream(f);
byte[] b = new byte[1024];
int count = 0;
int temp = 0;
while((temp = in.read()) != (-1)) {
b[count++] = (byte)temp;
}
in.close();
System.out.println(new String(b)); //这里若是没有new String的话看到的是编码地址
}
}
字符流
读取文件内容
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
char[] ch = new char[100];
Reader read = new FileReader(f);
int count = read.read(ch);
read.close();
System.out.println("读取的长度为:"+count);
System.out.println("内容为:"+new String(ch,0,count)); //这里若是没有new String的话看到的是编码地址
}
}
从文件中读取内容
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "D:"+File.separator+"hello.txt";
File f = new File(fileName);
char[] ch = new char[100];
Reader read = new FileReader(f);
int temp = 0;
int count = 0;
while((temp = read.read()) != (-1)) {
ch[count++] = (char)temp;
}
read.close();
System.out.println("读取的长度为:"+count);
System.out.println("内容为:"+new String(ch,0,count)); //这里若是没有new String的话看到的是编码地址
}
}
关于字节流和字符流的区别
实际上字节流在操作的时候本身是不会用到缓冲区的,是文件本身的直接操作的,但是字符流在操作的 时候下后是会用到缓冲区的,是通过缓冲区来操作文件的。
读者可以试着将上面的字节流和字符流的程序的最后一行关闭文件的代码注释掉,然后运行程序看看。你就会发现使用字节流的话,文件中已经存在内容,但是使用字符流的时候,文件中还是没有内容的,这个时候就要刷新缓冲区。
使用字节流好还是字符流好呢
答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的,包括图片等内容。但是字符只是在内存中才会形成的,所以在开发中,字节流使用广泛
文件的复制
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
if(args.length != 2) {
System.out.println("命令行参数输入有误,请检查");
System.exit(1);
}
File file1 = new File(args[0]);
File file2 = new File(args[1]);
if(!file1.exists()) {
System.out.println("被复制的文件不存在");
System.exit(1);
}
InputStream input = new FileInputStream(file1);
OutputStream output = new FileOutputStream(file2);
if((input != null) && (output != null)) {
int temp = 0;
while((temp = input.read()) != (-1)) {
output.write(temp);
}
}
input.close();
output.close();
}
}
OutputStreramWriter 和InputStreamReader类
整个IO类中除了字节流和字符流还包括字节和字符转换流。
OutputStreramWriter将输出的字符流转化为字节流
InputStreamReader将输入的字节流转换为字符流
但是不管如何操作,最后都是以字节的形式保存在文件中的。
将字节输出流转化为字符输出流
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "d:"+File.separator+"hello.txt";
File file = new File(fileName);
Writer out = new OutputStreamWriter(new FileOutputStream(file));
out.write("hello");
out.close();
}
}
将字节输入流变为字符输入流
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String fileName = "d:"+File.separator+"hello.txt";
File file = new File(fileName);
Reader read = new InputStreamReader(new FileInputStream(file));
char[] b = new char[100];
int len = read.read(b);
System.out.println(new String(b,0,len));
read.close();
}
}
前面列举的输出输入都是以文件进行的,现在我们以内容为输出输入目的地,使用内存操作流
ByteArrayInputStream 主要将内容写入内容
ByteArrayOutputStream 主要将内容从内存输出
使用内存操作流将一个大写字母转化为小写字母
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
String str = "ROLLENHOLT";
ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream output = new ByteArrayOutputStream();
int temp =0;
while((temp = input.read()) != -1) {
char ch = (char)temp;
output.write(Character.toLowerCase(ch));
}
String outStr = output.toString();
input.close();
output.close();
System.out.println(outStr);
}
}
管道流
管道流主要可以进行两个线程之间的通信。
PipedOutputStream 管道输出流
PipedInputStream 管道输入流
验证管道流
import java.io.*;
/**
*消息发送类
*/
class Send implements Runnable{
private PipedOutputStream out = null;
public Send() {
out = new PipedOutputStream();
}
public PipedOutputStream getOut() {
return this.out;
}
public void run() {
String message = "hello,Rollen";
try{
out.write(message.getBytes());
}catch(Exception e) {
e.printStackTrace();
}try{
out.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
/**
*接受信息类
*/
class Recive implements Runnable {
private PipedInputStream input = null;
public Recive() {
this.input = new PipedInputStream();
}
public PipedInputStream getInput() {
return this.input;
}
public void run() {
byte[] b = new byte[1000];
int len = 0;
try{
len = this.input.read(b);
}catch(Exception e) {
e.printStackTrace();
}try{
input.close();
}catch(Exception e) {
e.printStackTrace();
}
System.out.println("接收的内容为:"+(new String(b,0,len)));
}
}
/**
*测试类
*/
class Hello {
public static void main(String[] args) throws IOException {
Send send = new Send();
Recive recive = new Recive();
try{
//管道连接
send.getOut().connect(recive.getInput());
}catch(Exception e) {
e.printStackTrace();
}
new Thread(send).start();
new Thread(recive).start();
}
}
打印流 使用PrintStream进行输出
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
PrintStream print = new PrintStream(new FileOutputStream(new File("d:"+File.separator+"hello.txt")));
print.println(true);
print.println("Rollen");
print.close();
}
}
格式化输出
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
PrintStream print = new PrintStream(new FileOutputStream(new File("d:"+File.separator+"hello.txt")));
String name = "Rollen";
int age = 20;
print.printf("姓名:%s.年龄:%d.",name,age); //格式化输出
print.close();
}
}
使用OutputStream向屏幕上输出内容
import java.io.*;
class Hello {
public static void main(String[] args) throws IOException {
OutputStream out = System.out;
try{
out.write("hello".getBytes());
}catch(Exception e) {
e.printStackTrace();
}
try{
out.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
输入输出重定向
import java.io.*;
public class Hello {
public static void main(String[] args) {
//此刻直接输出到屏幕
System.out.println("hello");
File file = new File("d:"+File.separator+"hello.txt");
try{
System.setOut(new PrintStream(new FileOutputStream(file)));
}catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("这些内容在文件中才能够看到哦");
}
BufferedReader的小例子
注意: BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流,采用:
BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); |
/**
*使用缓冲区从键盘上读入内容
*/
import java.io.*;
class Hello {
public static void main(String[] args){
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String str = null;
System.out.println("请输入内容");
try{
str = buf.readLine();
}catch(IOException e ){
e.printStackTrace();
}
System.out.println("你输入的内容:"+str);
}
}
Scanner类
用Scanner类来进行数据输入
/**
*从键盘读取数据
*/
import java.util.*;
class Hello {
public static void main(String[] args){
Scanner sca = new Scanner(System.in);
//读取一个整数
int temp = sca.nextInt();
System.out.println(temp);
//读取浮点数
float flo = sca.nextFloat();
System.out.println();
//读取字符
}
}
其实Scanner可以接受任何的输入流
下面给一个使用Scanner类从文件中读出内容
import java.util.*;
import java.io.*;
class Hello {
public static void main(String[] args){
File file = new File("d:"+File.separator+"hello.txt");
Scanner sca = null;
try{
sca = new Scanner(file);
}catch(FileNotFoundException e) {
e.printStackTrace();
}
String str = sca.next();
System.out.println("从文件中读取的内容是:"+str);
}
}
数据操作流DataOutputStream、DataInputStream类
写入内容:ABC
import java.io.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"hello.txt");
char[] ch = {'A','B','C'};
DataOutputStream out = null;
out = new DataOutputStream(new FileOutputStream(file));//输出流
for(char temp:ch) {
out.writeChar(temp);//写入数据
}
out.close();
}
}
现在我们在上面例子的基础上,使用DataInputStream读出内容
import java.io.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"hello.txt");
DataInputStream input = new DataInputStream(new FileInputStream(file));
char[] ch = new char[10];
int count = 0;
char temp;
while((temp = input.readChar()) != 'C') {//读取数据
ch[count++] = temp;//跳到下一位
}
System.out.println(ch);
}
}
合并流 SequenceInputStream
SequenceInputStream主要用来将2个流合并在一起,比如将两个txt中的内容合并为另外一个txt。下面给出一个实例:
/**
*将两个文本文件合并为另外一个文本文件
*/
import java.io.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file1 = new File("d:"+File.separator+"hello1.txt");
File file2 = new File("d:"+File.separator+"hello2.txt");
File file3 = new File("d:"+File.separator+"hello.txt");
InputStream input1 = new FileInputStream(file1);//读取
InputStream input2 = new FileInputStream(file2);//读取
OutputStream output = new FileOutputStream(file3);//写入
//合并流
SequenceInputStream sis = new SequenceInputStream(input1,input2);
int temp = 0;
while((temp = sis.read()) != -1) {
output.write(temp);
}
input1.close();
input2.close();
output.close();
sis.close();
}
}
文件压缩 ZipOutputStream类
压缩一个文件(单文本文件)
import java.io.*;
import java.util.zip.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"hello.txt");
File zipFile = new File("d:"+File.separator+"hello.zip");
InputStream input = new FileInputStream(file);
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
//设置注释
zipOut.setComment("hello");
int temp = 0;
while((temp = input.read()) != -1) {
zipOut.write(temp);
}
input.close();
zipOut.close();
}
}
/**
*一次性压缩多个文件
*/
import java.io.*;
import java.util.zip.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"temp");
File zipFile = new File("d:"+File.separator+"zipFile.zip");
InputStream input = null;
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
//设置注释
zipOut.setComment("hello");
if(file.isDirectory()) {
File[] files = file.listFiles();
for(int i=0;i<files.length;++i) {
input = new FileInputStream(files[i]);
zipOut.putNextEntry(new ZipEntry(file.getName()+File.separator+files[i].getName()));
int temp=0;
while((temp = input.read()) != -1) {
zipOut.write(temp);
}
input.close();
}
}
zipOut.close();
}
}
/**
*获取压缩文件的文件名
*/
import java.io.*;
import java.util.zip.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"hello.zip");
ZipFile zipFile = new ZipFile(file);
System.out.println("压缩文件的名称为:"+zipFile.getName());
}
}
/**
*解压单个压缩文件
*/
import java.io.*;
import java.util.zip.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"hello.zip");
File outFile = new File("d:"+File.separator+"unZipFile.txt");
ZipFile zipFile = new ZipFile(file);
ZipEntry entry = zipFile.getEntry("hello.txt");
InputStream input = zipFile.getInputStream(entry);
OutputStream output = new FileOutputStream(outFile);
int temp = 0;
while((temp = input.read()) != -1) {
output.write(temp);
}
input.close();
output.close();
}
}
ZipInputStream类
当我们需要解压缩多个文件的时候,ZipEntry就无法使用了,如果想操作更加复杂的压缩文件,我们就必须使用ZipInputStream类
/**
*解压压缩文件jia duo
*/
import java.io.*;
import java.util.zip.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"zipFile.zip");
File outFile = null;
ZipFile zipFile = new ZipFile(file);
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
ZipEntry entry = null;
InputStream input = null;
OutputStream output = null;
while((entry = zipInput.getNextEntry()) != null) {
System.out.println("解压缩"+entry.getName()+"文件");
outFile = new File("d:"+File.separator+entry.getName());
if(!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdir();
}
if(outFile.exists()){
outFile.createNewFile();
}
input = zipFile.getInputStream(entry);
output = new FileOutputStream(outFile);
int temp =0;
while((temp = input.read()) != -1){
output.write(temp);
}
input.close();
output.close();
}
}
}
PsuhBackInputStream回退流
/**
*回退流操作---回避输入流
*可以把读取进来的某些数据重新回退到输入流的缓冲区之中
*/
import java.io.*;
public class Hello{
public static void main(String[] args) throws IOException {
String str = "hello,rollenholt";
PushbackInputStream push = null;//回退流
ByteArrayInputStream bat = null;//内存输入流
bat = new ByteArrayInputStream(str.getBytes());//实例化内存输入流
push = new PushbackInputStream(bat);//从内存中读取数据
int temp = 0;
while((temp = push.read()) != -1) {//不为空时,读取内存
if(temp == ',') {//以逗号作为回退的信号
push.unread(temp);
temp = push.read();//再读一次
System.out.print("回退"+(char)temp+")");
}else{
System.out.println((char)temp);
}
}
}
}
系统默认编码为:GBK
/**
*乱码的产生
*/
import java.io.*;
public class Hello{
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"hello.txt");
OutputStream out = new FileOutputStream(file);
byte[] bytes = "你好".getBytes("ISO8859-1");
out.write(bytes);
out.close();
}
}
对象的序列化
对象序列化就是把一个对象变为二进制数据流的一种方法。
一个类要想被序列化,就行必须实现java.io.Serializable接口。虽然这个接口中没有任何方法,就如同之前的cloneable接口一样。实现了这个接口之后,就表示这个类具有被序列化的能力。
/**
*实现具有实例化的类
*/
import java.io.*;
public class SerializableDemo implemnets Serializable {
private String name;
private int age;
public SerializableDemo() { //构造方法
}
public SerializableDemo(String name,int age) { //初始化参数
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "姓名:"+name+"年龄:"+age;
}
}
使类在被实例化成对象时又可调用的构造方法
无参与有参的区别,在被实例化调用时是否写入相关的参数与否
如:new Persion(“zhangsan”,30);
toStrng方法是为了方便操作字符如:System.out.println(xx);
在继续将序列化之前,先将一下ObjectInputStream和ObjectOutputStream这两个类
/**
*实现具有实例化的类
*/
import java.io.*;
public class Persion implemnets Serializable {
public Persion() {
}
public Persion(String name,int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "姓名:"+name+"年龄:"+age;
}
private String name;
private int age;
}
/**
*示范ObjectOutputStream
*/
public class ObjectOutputStreamDemo {
public static void main(String[] args) throws IOException {
File file = new File("d:"+File.separator+"hello.txt");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(new Persion("rollen",200));//写入数据
oos.close();
}
}
因为是二进制文件。虽然我们不能直接查看里面的内容,但是我们可以使用ObjectInputStream类查看
/**
*ObjectInputStream示范
*/
public class ObjectInputStreamDemo {
{
}
public static void main(String[] args) throws Exception {
File file = new File("d:"+File.separator+"hello.txt");
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
Object obj = input.readObject();//读取文件里的数据
input.close();
System.out.println(obj);
}
}
其实只有属性会被序列化。
两个包装类可用于输入流中读取对象类数据和将对象类型的数据写入到底层输入流。ObjectInputStream与ObjectOutputStream类所读写的对象必须实现了Serializable接口。
需要注意的是:对象中的transient和static类型的成员变量不会被读取和写入
Externalizable接口
被Serializable接口声明的类的对象的属性都将被序列化,但是如果想自定义序列化的内容的时候,就需要实现Externalizable接口。
当一个类要使用Externalizable这个接口的时候,这个类中必须要有一个无参的构造函数,如果没有的话,在构造的时候会产生异常,这是因为在反序列话的时候会默认调用无参的构造函数。
/**
*序列化和饭序列化的操作
*/
public class ExternalizableDemo {
public static void main(String[] args) throws Exception {
ser(); //序列化
dser(); //反序列化
}
public static void ser() throws Exception {//序列化
File file = new File("d:"+File.separator+"hello.txt");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(new Persion("rollen",20));
out.close();
}
public static void dser() throws Exception {//反序列化
File file = new File("d:"+separator+"hello.txt");
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
Object obj = input.readOject();
input.close();
System.out.pritnln(obj);
}
}
class Persion implements Externalizable
{
public Persion() {}
public Persion() {
this.name = name;
this.age = age;
}
@Override
public String toString(){
return "姓名:"+name+"年龄:"+age;
}
// 复写这个方法,根据需要可以保存的属性或者具体内容,在序列化的时候使用
@Override
public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
this.name = (String) in.readObject();
this.age =in.readInt();
}
private String name;
private int age;
}
Serializable接口实现的操作其实是一个对象中的全部属性进行序列化,当然也可以使用我们上使用是Externalizable接口以实现部分属性的序列化,但是这样的操作比较麻烦,
当我们使用Serializable接口实现序列化操作的时候,如果一个对象的某一个属性不想被序列化保存下来,那么我们可以使用transient关键字进行说明:
/**
*序列化和反序列化的操作
*/
public class ExternalizableDemo {
public static void main(String[] args) throws Exception {
ser(); //序列化
dser(); //反序列化
}
public static void ser() throws Exception {
File file = new File("d:"+File.separator+"hello.txt");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(new Persion("rollen",20));
out.close();
}
public static void dser() throws Exception {
File file = new File("d:"+separator+"hello.txt");
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
Object obj = input.readOject();
input.close();
System.out.pritnln(obj);
}
}
class Persion implements Externalizable
{
public Persion() {}
public Persion() {
this.name = name;
this.age = age;
}
@Override
public String toString(){
return "姓名:"+name+"年龄:"+age;
}
// 复写这个方法,根据需要可以保存的属性或者具体内容,在序列化的时候使用
@Override
public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
this.name = (String) in.readObject();
this.age =in.readInt();
}
//注意这里
private transient String name;//怎么实现的呢
private int age;
}
序列化一组对象
/**
*序列化一组对象
**/
import java.io.*;
public class SerDemo{
public static void main(String[] args) throws Exception {
Studnet[] stu = {new Student("hello",20),
new Student("world",30),
new(Student("rollen",40))};
ser(stu);
Object[] obj = dser();
for(int i=0;i<obj.length;++i) {
Student s = (Student) obj[j];
System.out.println(s);
}
}
//序列化
public static void ser(Object[] obj) throws Exception {
File file = new File("d:"+File.separator+"hello.txt");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(obj);//数据写入
out.close();
}
//反序列化
public static Object[] dser() throws Exception {
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
Object[] obj = (Object)input.readObject();//数据读取
input.close();
return obj;
}
}
class Student implements Serializable {
public Student() {
}
public Student(String name,int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
}
高级Java面试系列
可变参数,断言,垃圾回收,初始化器,令牌化,日期,日历等等Java核心问题
字符串有整形的相互转换
String a = String.valueOf(2);
int i = Integer.parseInt(a);
向文件末尾添加内容
BufferedWriter out = null;
try{
out = new BufferedWriter(new FileWriter("filename",true));
out.write("aString");
}catch(IOException e) {
//error processing code
}finally {
if(out != null) {
out.close();
}
}
得到当前的方法名
String methodName = Thread.currentThread().getStacktrace()[1].getMethmodName();
转字符串到日期
SimpleDateFormat format = new SimpleDateFormat(“dd.MM.yyyy”);
Date date = format.parse(myString);
使用JDBC连接Oracle
public class OracleJdbcTest{
String driverClass = "oracle.jdbc.driver.OrackeDriver";
Connection con;
public void init(FileInputStream fs) throws ClassNotFoundException,SQLException,FileNotFoundException,IOException {
Properties props = new Properties();
props.load(fs);
String url = props.getProperty("db.url");
String userName = props.getProperty("db.user");
String password = props.getProgetty("db.password");
Class.forName(driverClass);
con = DriverManager.getConnection(url,userName,password);
}
public void fetch() throws SQLException,IOException {
PreparedStatement ps = con.prepareStatement("select SYSTEM from dual");
ReslutSet rs = ps.executeQuery();
while(rs.next()) {
//do the thing you do
}
rs.close();
ps.close();
}
public static void main(String[] args) {
OracleJdbcTest test = new OracleJdbcTest();
test.init();
test.fetch();
}
}
把java util.Date转成java.sql.Date
java.util.Date utilDate = new java.util.Date();
java.sal.Date sqlDate = new java.sql.Date(utilDate.getTime());