java I/O操作_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java I/O操作

java I/O操作

 2012/2/16 9:09:59  amioxm  程序员俱乐部  我要评论(0)
  • 摘要:importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.InputStream;importjava.io
  • 标签:Java 操作
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PushbackInputStream;
import java.io.RandomAccessFile;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


public class Main {
/*
* 创建文件(createNewFile)或者文件夹(mkDir)
*/
public void createFile(String dir) throws Exception{
File file = new File(dir);
if(file.exists()){
file.delete();
}
/*
* file.delete(),删除文件或者文件夹;
* file.exists(),判断文件或文件夹是否存在;
* file.createNewFile(),创建文件;
* file.mkdir(),创建文件夹;
*/
if(file.createNewFile()){
System.out.println("文件创建成功\n");
}else{
System.out.println("文件创建失败\n");
}
}
/*
* 列出路径下的文件或文件夹
*/
public void queryDir(String dir) throws Exception{
File file = new File(dir);
if(file.isDirectory()){
/*
* file.isDirectory(),判断是否为目录;
* file.list(),列出所有文件名称;
* file.listFiles(),列出所有文件对象;
* file.getPath()/file.getAbsolutePath()/file.getCanonicalPath(),相对路径下的取值不同;
*/
File[] names = file.listFiles();
for(File str : names){
System.out.println(str.getPath());
}
System.out.println("--------------------------------------");
for(File str : names){
System.out.println(str.getAbsolutePath());
}
System.out.println("--------------------------------------");
for(File str : names){
System.out.println(str.getCanonicalPath());
}
}else{
System.out.println(file.getName());
}
}
/*
* 递归搜索指定路径下的特定文件
*/
public void searchDir(String dir,String filename) throws Exception{
File directory = new File(dir);
boolean flag = false;
if(directory!=null){
if(directory.isDirectory()){

File[] files = directory.listFiles();
for(File temfile : files){
System.out.println(temfile.getCanonicalPath());
if(temfile.getName().equals(filename)){
flag = true;
System.out.println("---------------发现符合条件的文件-----------------");
System.out.println(temfile.getCanonicalPath());
System.out.println("-------------------------------------------------");
}
searchDir(temfile.getCanonicalPath(),filename);
}
}
}
if(!flag){
System.out.println("---------------未发现符合条件的文件-----------------");
}
}

/*
* 使用RandomAccessFile写入文件
*/
public void write(String filePath) throws Exception{
File file = new File(filePath);
RandomAccessFile raf = new RandomAccessFile(file,"rw");
        raf.writeChar('a');
        raf.writeBytes("情人节");
        raf.write(2);
        raf.close();
}

/*
* 使用FileOutputSteam写入文件
* 使用FileInputSteam读入文件
*/
public void write2(String filePath,String src) throws Exception{
/*
* new FileOutputStream(new File(filePath),true),代表追加内容;
* new FileOutputStream(new File(filePath)),覆盖原有内容;
*/
InputStream fis = new FileInputStream(new File(src));
OutputStream fos = new FileOutputStream(new File(filePath),true);
byte[] bytes = new byte[1024];
while(fis.available()>0){
while(fis.read(bytes)!=-1){
fos.write(bytes);
}
}
fis.close();
        fos.close();
}

/*
* 使用FileWriter写入文件
* 使用FileReader读入文件
*/
public void write3(String filePath,String src) throws Exception{
/*
* new FileReader(new File(filePath),true),代表追加内容;
* new FileReader(new File(filePath)),覆盖原有内容;
*/
int temp = 0;
FileReader reader = new FileReader(new File(src));
FileWriter writer = new FileWriter(new File(filePath));
while((temp=reader.read())!=-1){
writer.write(temp);
}
writer.flush();
reader.close();
writer.close();
}

/*
* OutputStreamWriter将输出的字符流转化为字节流;
       InputStreamReader将输入的字节流转换为字符流;
                  但是不管如何操作,最后都是以字节的形式保存在文件中的。
*/
public void write4(String src,String filePath) throws Exception{
int temp = 0;
InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(src)));
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File(filePath)));
while((temp = isr.read())!=-1){
osw.write(temp);
}
osw.flush();
isr.close();
osw.close();
}

/*
* 使用内存操作流
       ByteArrayInputStream 主要将内容写入内存
       ByteArrayOutputStream 主要将内容从内存输出
*/
public void write5(String str) throws Exception{
        ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());       
        ByteArrayOutputStream output=new ByteArrayOutputStream();       
        int temp=0;       
        while((temp=input.read())!=-1){           
        char ch=(char)temp;           
        output.write(ch);       
        }       
        String outStr=output.toString();       
        input.close();       
        output.close();       
        System.out.println(outStr);
}

/*
* 管道流主要可以进行两个线程之间的通信。
       PipedOutputStream 管道输出流
       PipedInputStream 管道输入流
*/
class Send implements Runnable {

private PipedOutputStream out=null;   
public Send() {
out=new PipedOutputStream();
}   

public PipedOutputStream getOut(){       
return this.out;   
}   
public void run(){       
String message="管道输出流";       
try{
out.write(message.getBytes());       
}catch (Exception e) {           
e.printStackTrace();       
}try{           
out.close();       
}catch (Exception e) {           
e.printStackTrace();       
}   
}

}

class Receive implements Runnable{

private PipedInputStream input=null; 

public Receive(){       
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)));   
}
       
}

/*
* 用Scanner类来进行数据输入
*/
public void scanner() throws Exception{
Scanner sc = new Scanner(System.in);
System.out.println("请输入:");
while(sc.hasNext()){
String str = sc.next();
System.out.println(str);
}
sc.close();
}

public void scannerFromFile(String filePath) throws Exception{
File file = new File(filePath);
if(file.exists() && !file.isDirectory()){
Scanner sc = new Scanner(file);
while(sc.hasNext()){
String str = sc.next();
System.out.println(str);
}
sc.close();
}else{
return;
}
}

/*
* SequenceInputStream主要用来将2个流合并在一起
*/
public void combineInputStream(String srcFile1,String srcFile2,String destFile) throws Exception{
InputStream input1 = new FileInputStream(new File(srcFile1));
InputStream input2 = new FileInputStream(new File(srcFile2));
OutputStream dest = new FileOutputStream(new File(destFile));

SequenceInputStream sis = new SequenceInputStream(input1,input2);
int temp = 0;
while((temp = sis.read()) != -1){
dest.write(temp);
}
input1.close();
input2.close();
dest.close();
sis.close();
}

/*
* 使用ZipOutputStream压缩文件或文件夹
*/
public void zip(String filePath,String zipPath) throws Exception{
File file = new File(filePath);
        File zipFile = new File(zipPath);
        if(!zipFile.exists()){
        if(!zipFile.isDirectory()){
        if(!zipFile.createNewFile()){
            return;
            }else{
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            zipOut.setComment("设置注释");
            if(file.isDirectory()){
            File[] files = file.listFiles();
            for(File tempFile : files){
            InputStream input = new FileInputStream(tempFile);       
                            ZipEntry ze = new ZipEntry(tempFile.getName());
                            zipOut.putNextEntry(ze);       
                            int temp = 0;       
                            while((temp = input.read()) != -1){           
                            zipOut.write(temp);       
                            }       
                            input.close();
            }
            zipOut.close();
            }else{
            InputStream input = new FileInputStream(file);       
                        ZipEntry ze = new ZipEntry(file.getName());//关键点1
                        zipOut.putNextEntry(ze);//关键点2       
                        int temp = 0;       
                        while((temp = input.read()) != -1){           
                        zipOut.write(temp);       
                        }       
                        input.close();       
                        zipOut.close();
            }
            }
        }
        }
       
}

/*
* 使用ZipFile解压文件
*/
@SuppressWarnings("unchecked")
public void unzip(String zipPath) throws Exception{
File file = new File(zipPath);
ZipFile zipFile = new ZipFile(file);
Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>)zipFile.entries();
while(enumeration.hasMoreElements()){
ZipEntry ze = enumeration.nextElement();
File outFile = new File("D:" + File.separator + ze.getName());
InputStream input = zipFile.getInputStream(ze);
OutputStream output = new FileOutputStream(outFile);
int temp = 0;
while((temp = input.read()) != -1){
output.write(temp);
}
input.close();
output.close();
}
}

/*
* PushBackInputStream回退流
*/
public void pushBack() throws Exception{
System.out.println("系统默认编码为:" + System.getProperty("file.encoding"));
String str = "public static void main(String[] args){";
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.println("(回退" + (char) temp + ") ");
}else{
System.out.println((char) temp);
}
}
}

/*
* 序列化
* Serializable接口实现的操作其实是把一个对象中的全部属性进行序列化
* 如果一个对象的某一个属性不想被序列化保存下来,那么我们可以使用transient关键字进行说明
*/
public void toSerialize(Person person) throws Exception{
File file = new File("D:" + File.separator + "person.txt");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(person);
oos.close();
}

    public void unSerialize() throws Exception{
    File file = new File("D:" + File.separator + "person.txt");
    ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
    Object obj = input.readObject();
    input.close();
    System.out.println(obj);
}

public static void main(String[] args) throws Exception{
Main main = new Main();
//System.out.println("D:"+File.separator+"hello"+File.separator+"hello.txt");
//main.createFile("D:"+File.separator+"hello"+File.separator+"hello.txt");

//main.queryDir(".");

//main.searchDir(".", "Maina.java");

//main.write4("D:"+File.separator+"qingrenjie.txt","D:"+File.separator+"qingrenjie2.txt");

//main.write5("你妹的情人节!!");

/*
Send send = main.new Send();
Receive receive = main.new Receive();
send.getOut().connect(receive.getInput());
new Thread(send).start();
new Thread(receive).start();
*/

//main.scanner();

//main.scannerFromFile("D:"+File.separator+"qingrenjie.txt");

//main.combineInputStream("D:"+File.separator+"qingrenjie.txt", "D:"+File.separator+"qingrenjie2.txt", "D:"+File.separator+"qingrenjie3.txt");

//main.zip("D:"+File.separator+"zip", "D:"+File.separator+"forZIP.zip");

//main.unzip("D:"+File.separator+"forZIP.zip");

//main.pushBack();

Person person = new Person("nimeia",25);
main.toSerialize(person);

main.unSerialize();
}
}
发表评论
用户名: 匿名