day08

文件过滤

(各种方法查阅api.)

先创建数组,为目录下所有的文件
然后遍历数组用
判断isDirectory()是否文件夹
然后getName().endWith(“.zip”)
如果是 打印文件名,如果是文件夹,就进入文件夹

import java.io.File;

public class BianLi {
    public static void main(String[] args) {
        bianli("e:\\");
    }

    public static void bianli(String filepath) {
        File file = new File(filepath);
        File[] list = file.listFiles();
        for (int i = 0; i < list.length; i++) {
            if (list[i].isDirectory()) {
                bianli(list[i].getAbsolutePath());
            } else {
                if (list[i].getName().endsWith(".zip")) {
                    System.out.println(list[i].getAbsolutePath());
                }
            }
        }
    }
}

寻找目录下所有的zip文件
运行结果:
这里写图片描述

接口filenameFilter()

实现了接口的方法来检索目录下是否有相应文件,缺点是无法访问子目录

import java.io.File;
import java.io.FilenameFilter;

public class ZipFileNameFilter implements FilenameFilter{

    public boolean accept(File dir, String name) {

        return name.endsWith("zip");
    }

}
import java.io.File;
import java.nio.channels.AcceptPendingException;

import javax.swing.text.StyledEditorKit.ForegroundAction;

public class ZipBianLi {
    public static void main(String[] args) {
        ZipFileNameFilter zfn = new ZipFileNameFilter();
        File file = new File("e:\\");
        File[] arr = file.listFiles(zfn);
        boolean b0 = false;
        for (int i = 0; i < arr.length; i++) {
            String s = arr[i].getAbsolutePath();
            System.out.println(s);
        }
    }
}

运行结果:这里写图片描述

FileOutputStream

写一个文件
先判断目录下有没有相应的文件 对象.exists()
没有就创建文件 对象.creatNewFile()
外部初始化FileOutputStream
try内部new一个FileOutputStream的文件
out.write(字节);
刷新out.flush()

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class CreatNewFile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        File file = new File("e://11.txt");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(file);
            fout.write(s.getBytes());
            fout.flush();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

运行结果:这里写图片描述
这里写图片描述

利用缓冲区来写文件

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class WriteBuffered {
    public static void main(String[] args) {
        File file = new File("e://22.txt");
        try {
            FileOutputStream os = new FileOutputStream(file);
            OutputStreamWriter sw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(sw);
            bw.write("3211111111");
            bw.newLine();
            bw.write("654654654654");
            os.flush();
            sw.flush();
            bw.flush();
            os.close();
            sw.close();
            bw.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

运行结果:这里写图片描述

复制一个文件

创建一个方法,需要输入源文件和拷贝文件
需要判断是否源文件和拷贝文件不存在
建立出两种文件的对象
建立输入输出流的对象
建立字节数组
循环判断
用read()方法判断是否到结尾
先读取源文件的内容
用 对象.write(array,0,i)函数写入拷贝文件
主函数调用方法名(a,b)a源文件,b拷贝文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFiles {
    public static void copyFile(String a,String b){
        File from = new File("e://22.txt");
        File to = new File("e://33.txt");
        if(!from.exists()){
            System.out.println("源文件不存在");
        }
        if(!to.exists()){
            try {
                to.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(to);
            FileInputStream in = new FileInputStream(from);
            byte[] array = new byte[1024];
            int i = 0;
            while(i!=-1){
                i = in.read(array);
                if(i!=-1){
                    out.write(array, 0, i);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    public static void main(String[] args) {
        copyFile("e://22.txt", "e://33.txt");
    }
}

运行结果:这里写图片描述

读取文件的内容

import java.io.*;

public class ReadBuffered {
    public static void main(String[] args) {
        File file= new File("e://22.txt");
        try {
            FileInputStream is = new FileInputStream(file);
            InputStreamReader sr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(sr);
            String s = br.readLine();
            while(s!=null){
                System.out.println(s);
                s = br.readLine();
            }
            is.close();
            sr.close();
            br.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 



    }
}

运行结果:这里写图片描述

PrintStream

System.setOut(对象)可以把系统输出的值传给对象

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class SetOutTest {
    public static void main(String[] args) {
        File file = new File("e://22.txt");
        try {
            PrintStream ps = new PrintStream(file);
            System.setOut(ps);
            System.out.println("998456132123123");
            System.out.println("grg123d1f23dsf1");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

运行结果:这里写图片描述

XML

XML是一种简单的数据存储语言,使用一系列简单的标签简述数据
主要部分是元素,有开始标签结束标签,可以嵌套
DocumentBuilderFactory
解析XML有两种: DOM SAX
使用DOM解析必须生成DOM对象
Document 对象,生成DOM对象

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMjiexi {
    public static void main(String[] args) {

        File file = new File("e://321.txt");

        DocumentBuilderFactory  dbf =DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            NodeList weathers = doc.getElementsByTagName("Weather");
            for (int i = 0; i < weathers.getLength(); i++) {
                Node wea = weathers.item(i);
                NamedNodeMap map = wea.getAttributes();
                System.out.println("123465"+map.getNamedItem("name").getNodeValue());
                for (Node node = wea.getFirstChild();node != null;node = node.getNextSibling()) {
                    if(node.getNodeType()==Node.ELEMENT_NODE){
                        System.out.println(node.getNodeName());
                        if(node.getFirstChild()!=null){
                            System.out.println(node.getFirstChild().getNodeValue());
                        }
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

运行结果:
这里写图片描述

SAX解析

import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXHandler extends DefaultHandler{

    @Override
    public void characters(char[] arg0, int arg1, int arg2) throws SAXException {

        super.characters(arg0, arg1, arg2);
        System.out.println("文档内容"+new String(arg0,arg1,arg2));
    }

    @Override
    public void endDocument() throws SAXException {

        super.endDocument();
        System.out.println("结束解析文档");
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        super.endElement(uri, localName, qName);
        System.out.println("结束标签"+qName);
    }

    @Override
    public void startDocument() throws SAXException {

        super.startDocument();
        System.out.println("开始解析文档");
    }

    @Override
    public void startElement(String uri, String localName, String qName,Attributes att) throws SAXException {
        super.startElement(uri, localName, qName,att);
        System.out.println("开始标签"+qName);
        if(qName.equals("Weather")){
            System.out.println("Attributes"+att.getValue("name"));
        }
    }

}
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.helpers.*;;
public class Test {
    public static void main(String[] args) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        File file = new File("e://321.txt");
        try{
            SAXParser parser = factory.newSAXParser();
            SAXHandler handler = new SAXHandler();
            parser.parse(file,handler);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

运行结果:这里写图片描述

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值