JDK7的文件操作

添加删除文件的代码:
//创建新路径
Path newFile = Paths.get("test1");
try {
  Files.deleteIfExists(newFile);
  newFile = Files.createFile(newFile);
} catch (IOException ex) {
  System.out.println("Error creating file");
}
System.out.println(Files.exists(newFile));


读写文件:

代码片段如下:
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
 
/**
 *
 * @author Eric Bruno
 */
public class Java7FileIO {
    String myXML =  "<Configuration>\n" +
                    "   <Server>\n" +
                    "       <Name>MyServer</Name>\n" +
                    "       <Address>192.168.0.1</Address>\n" +
                    "   </Server>\n" +
                    "   <RetryCount>10</RetryCount>\n" +
                    "   <Logs>\n"+
                    "       <FilePath>/logs/out.txt</FilePath>\n"+
                    "       <Level>INFO</Level>\n"+
                    "   </Logs>\n"+
                    "</Configuration>";
 
    public static void main(String[] args) {
        Java7FileIO j7fio = new Java7FileIO();
        List<String> lines = null;
         
        // 写文件
        j7fio.writeFileBytes("config.xml", j7fio.myXML);
 
        // 一次性读取小文件
        System.out.println("\n-- TEST 1 ---------------------------");
        String config = new String(j7fio.readSmallFileBytes("config.xml"));
        System.out.println(config);
 
        // 一次性读取小文件的所有行
        System.out.println("\n-- TEST 2 ---------------------------");
        lines = j7fio.readSmallFileLines("config.xml");
        for ( String line: lines )
            System.out.println(line);
        
        // 读取大文件的所有行
        System.out.println("\n-- TEST 3 ---------------------------");
        lines = j7fio.readLargeFileLines("log.txt");
        for ( String line: lines )
            System.out.println(line);
 
        // 读取大文件的所有行
        System.out.println("\n-- TEST 4 ---------------------------");
        lines = j7fio.readLargeFileLinesMixed("log.txt");
        for ( String line: lines )
            System.out.println(line);
    }
     
    public Java7FileIO() {
    }
     
    public byte[] readSmallFileBytes(String name) {
        byte[] filearray = null;
        try {
            Path path = FileSystems.getDefault().getPath(".", name);
            return Files.readAllBytes(path);
        }
        catch ( IOException ioe ) {
            ioe.printStackTrace();
        }
        return filearray;
    }
     //读取小文件的所有行
    public List<String> readSmallFileLines(String name) {
      
          try {
                  return Files.readAllLines(
                            FileSystems.getDefault().getPath(".", name),
                            Charset.defaultCharset() );
        }
        catch ( IOException ioe ) {
            ioe.printStackTrace();
        }
        return null;
    }
     //读取大文件的所有行,为了性能,使用了bufferedreader
    public List<String> readLargeFileLines(String name) {
        try {
            BufferedReader reader =
                Files.newBufferedReader(
                    FileSystems.getDefault().getPath(".", name),
                    Charset.defaultCharset() );
 
            List<String> lines = new ArrayList<>();
            String line = null;
            while ( (line = reader.readLine()) != null )
                lines.add(line);
 
            return lines;
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }       
        return null;
    }
     
    public List<String> readLargeFileLinesMixed(String name) {
        try {
            Path path = FileSystems.getDefault().getPath(".", name);
            InputStream in = Files.newInputStream(path);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
             
            List<String> lines = new ArrayList<>();
            String line = null;
            while ( (line = reader.readLine()) != null )
                lines.add(line);
 
            return lines;
        }
        catch ( IOException ioe ) {
            ioe.printStackTrace();
        }
         
        return null;
    }
     
    //写文件
    void writeFileBytes(String filename, String content) {
        try {
            Files.write( FileSystems.getDefault().getPath(".", filename),
                         content.getBytes(),
                         StandardOpenOption.CREATE);
        }
        catch ( IOException ioe ) {
            ioe.printStackTrace();
        }
    }
     
   //写文件,可以设置字符集
    void writeFileBytesBuffered(String filename, String content) {
        try {
            BufferedWriter writer =
                Files.newBufferedWriter(
                        FileSystems.getDefault().getPath(".", filename),
                        Charset.forName("US-ASCII"),
                        StandardOpenOption.CREATE);
 
            writer.write(content, 0, content.length());
        }
        catch ( IOException ioe ) {
            ioe.printStackTrace();
        }
    }
}

原文链接:http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值