第二周第四天(解析/过滤文件/找d盘里的所有txt文件/FileInputStream/FileOutputStream/拷贝文件/readLine读取一个文本行/在一个文档里写入内容)

来源:互联网 发布:软件 新技术 编辑:程序博客网 时间:2024/06/05 19:33

过滤文件

package com.day4_2015_7_23;import java.io.File;public class Test {public static void main(String[] args) {    ergodicFile("d:\\");}    public static void ergodicFile(String filePath){    File file = new File(filePath);    //public File(String pathname)通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例    File[] files = file.listFiles();//file.listFiles() 返回一个抽象路径名数组,    //这些路径名表示此抽象路径名表示的目录中的文件。    for (int i = 0; i < files.length; i++) {        if(files[i].isDirectory()){            //files[i].isDirectory()测试此抽象路径名表示的文件是否是一个目录。            ergodicFile(files[i].getAbsolutePath());            //files[i].getAbsolutePath()返回此抽象路径名的绝对路径名字符串。        }else{            if(files[i].getName().endsWith(".zip")){                System.out.println(files[i].getAbsolutePath());            }        }    }    }}

找d盘里的所有txt文件

package com.day4_2015_7_23;import java.io.File;import java.io.FilenameFilter;import java.nio.file.Files;public class ZipFilenameFilter implements FilenameFilter{    @Override    public boolean accept(File dir, String name) {        return name.endsWith(".txt");    }}package com.day4_2015_7_23;import java.io.File;public class Test1 {    public static void main(String[] args) {    ZipFilenameFilter filter = new ZipFilenameFilter();    File file = new File("d:\\");    File[] files = file.listFiles(filter);    for (int i = 0; i < files.length; i++) {        System.out.println(files[i].getAbsolutePath());    }}}

FileInputStream

package com.day4_2015_7_23;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class Test2 {public static void main(String[] args) {    File file =new File("d:\\11.txt");    FileInputStream in =null;    try{        in = new FileInputStream(file);        byte[] arry = new byte[1024];        int i = in.read(arry);        while(i != -1){            System.out.println(new String(arry,0,i));            i=in.read(arry);            }    }catch (FileNotFoundException e) {            // TODO: handle exception            e.printStackTrace();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            finally{                if(in!=null);{                try {                    in.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                }            }}}

FileOutputStream

//*************FileOutputStream*************//package com.day4_2015_7_23;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Scanner;public class Test3 {    public static void main(String[] args) {    Scanner scanner = new Scanner(System.in);    String s=scanner.next();    File file =new File("d:\\33.txt");    if(!file.exists()){        try {            file.createNewFile();        } catch (IOException e) {            // TODO: handle exception            e.printStackTrace();        }    }    FileOutputStream out = null;    try {        out = new FileOutputStream(file);        out.write(s.getBytes());        out.flush();    } catch (FileNotFoundException e) {        // TODO: handle exception    e.printStackTrace();    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    finally{        if(out!=null);{        try {            out.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        }    }}}

拷贝文件

//***********拷贝文件**************//package com.day4_2015_7_23;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class Test4 {    public static void main(String[] args) {    copy("d:\\22.txt","d:\\33.txt");}//写一个copy的方法    public static void copy(String path,String copy){    File source = new File(path);    File file = new File(copy);    if(!source.exists()){        System.out.println("拷贝的源文件不存在");        return;    }    //如果要拷贝的文件不存在就新建一个文件    if(!file.exists()){        try{            file.createNewFile();        }catch(IOException e){            e.printStackTrace();        }    }    try {        FileInputStream sourceIn = new FileInputStream(source);        FileOutputStream copyOut = new FileOutputStream(copy);        byte[] array = new byte[1024];        int i = 0;        while(i !=-1){            i = sourceIn.read(array);            if(i!=-1){                copyOut.write(array,0,i);            }        }        sourceIn.close();        copyOut.flush();        copyOut.close();    } catch (FileNotFoundException e) {        // TODO: handle exception        e.printStackTrace();    }catch(IOException e){        e.printStackTrace();    }} }

readLine读取一个文本行

//***********readLine读取一个文本行*************//package com.day4_2015_7_23;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class Test5 {    public static void main(String[] args) {        File file = new File("d:\\22.txt");        try {            FileInputStream is = new FileInputStream(file);            InputStreamReader read = new InputStreamReader(is);            BufferedReader br = new BufferedReader(read);            String s = br.readLine();            while(s!=null){                System.out.println(s);                s=br.readLine();            }            br.close();            read.close();            is.close();            } catch (FileNotFoundException e) {                // TODO Auto-generated catch block                  e.printStackTrace();            }catch(IOException e){                e.printStackTrace();            }    }    }

在一个文档里写入内容

//*********在一个文档里写入内容**********//package com.day4_2015_7_23;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 Test6 {    public static void main(String[] args) {        File file = new File("d:\\22.txt");        try {            FileOutputStream os = new FileOutputStream(file);            OutputStreamWriter writer = new OutputStreamWriter(os);            BufferedWriter bw = new BufferedWriter(writer);            bw.write("你好");            bw.newLine();            bw.write("你好");            bw.flush();            writer.flush();            os.flush();            bw.close();            writer.close();            os.close();        } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

修改文档内容

///*******修改文档内容*****//package com.day4_2015_7_23;import java.io.File;import java.io.FileNotFoundException;import java.io.PrintStream;public class Test7 {public static void main(String[] args) {    File file = new File("d:\\11.txt");    try {        PrintStream ps = new PrintStream(file);        System.setOut(ps);        System.out.println("你好啊");    } catch (FileNotFoundException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }}}

DOM解析

package com.day4_2015_7_23;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.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class Test8 {    public static void main(String[] args) {    // 创建DOM解析器的工厂        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        try {            // 从DOM工厂获得DOM 解析器            DocumentBuilder db = dbf.newDocumentBuilder();            // 解析XML文档,得到一个Document,即DOM树            Document doc = db.parse("xml.xml");            // 得到所有的pet节点列表信息/得到文档中的所有weather标签            NodeList list = doc.getElementsByTagName("Weather");            // 轮循xml信息            for (int i = 0; i < list.getLength(); i++) {                Node node = list.item(i);                // node.getFirstChild()得到weather标签的第一个子标签city                // node1.getNextSibling()得到city标签的下一个子标签                for (Node node1 = node.getFirstChild(); node1 != null; node1 = node1.getNextSibling())                    if (node1.getNodeType() == node1.ELEMENT_NODE) {// 判断节点类型是ELEMENT_NODE                        if (node1.getFirstChild() != null) {// 得到该节点的第一个子节点不能为空                            System.out.println(node1.getFirstChild().getNodeValue());                        }                    }            }        } catch (ParserConfigurationException e) {            e.printStackTrace();        } catch (SAXException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

重写SAXException的一些方法,然后解析文件

package com.day4_2015_7_23;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class MySAXHandler extends DefaultHandler {    @Override    public void startDocument() throws SAXException {        // TODO Auto-generated method stub        super.startDocument();        System.out.println("开始解析");    }    @Override    public void endDocument() throws SAXException {        // TODO Auto-generated method stub        super.endDocument();        System.out.println("解析结束");    }    @Override    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {        // TODO Auto-generated method stub        super.startElement(uri, localName, qName, attributes);        System.out.println("开始标签"+qName);        if(qName.equals("Weather")){            System.out.println("Attributes"+attributes.getValue("name"));        }    }    @Override    public void endElement(String uri, String localName, String qName) throws SAXException {        // TODO Auto-generated method stub        super.endElement(uri, localName, qName);        System.out.println("结束标签"+qName);    }    @Override    public void characters(char[] ch, int start, int length) throws SAXException {        // TODO Auto-generated method stub        super.characters(ch, start, length);        System.out.println("标签内容"+new String(ch,start,length));    }}package com.day4_2015_7_23;import java.io.File;import java.io.IOException;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.SAXException;public class Test9 {    public static void main(String[] args) {    SAXParserFactory factory= SAXParserFactory.newInstance();    File f = new File("d:\\xml.xml");       try {            SAXParser parser = factory.newSAXParser();            MySAXHandler handler = new MySAXHandler();            parser.parse(f, handler);        }catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            catch (ParserConfigurationException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (SAXException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    } }
0 0
原创粉丝点击