JAVA基础之文件流输入输出

过去的文件流输出写法:

File f=new File("/Users/buxuesong/Documents/svn_code/demo/test.txt");
//OutputStream
OutputStream output = new FileOutputStream(f);

byte byteVal = 100;
output.write(byteVal);

byte[] byteBuff = {0,63,127};
output.write(byteBuff);

output.flush();
output.close();

//Writer
Writer writer = new FileWriter(f,true);
char charVal = 'a';
writer.write(charVal);

char[] charBuff = {'a','b','c'};
writer.write(charBuff);

过去文件流输入写法:

File f=new File("/Users/buxuesong/Documents/svn_code/demo/test.txt");
//InputStream
InputStream input = new FileInputStream(f);
int intVal;
while((intVal = input.read())>=0){
    byte byteVla = (byte) intVal;
    System.out.println(byteVla);
}

input = new FileInputStream(f);
int length;
byte[] byteBuff = {1,2,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4};

while((length = input.read(byteBuff))>=0){
    for(int i = 0;i=0){
    char charVal = (char) intVal;
    System.out.println(charVal);
}
reader = new FileReader(f);
char[] charBuff = {'a','b','c'};
while((length = reader.read(charBuff))>=0){
    for(int i=0;i

try with resource写法

try(BufferedReader br = new BufferedReader(new FileReader("/Users/buxuesong/Documents/svn_code/demo/test.txt"))){
    while ((intVal = br.read())>=0){
        char charVal = (char) intVal;
        System.out.println("BufferedReader"+charVal);
    }

}
try(BufferedReader br = new BufferedReader(new FileReader("/Users/buxuesong/Documents/svn_code/demo/testBufferedWriter.txt"))){
    String inValue;
    while((inValue = br.readLine())!=null){
        System.out.println("inValue"+inValue);
    }
}

新的输入输出写法:

try(BufferedReader br = Files.newBufferedReader(Paths.get("/Users/buxuesong/Documents/svn_code/demo/testBufferedWriter.txt"))){
    String inValue;
    while((inValue = br.readLine())!=null){
        System.out.println("Files.newBufferedReader="+inValue);
    }
}

List lines = Files.readAllLines(Paths.get("/Users/buxuesong/Documents/svn_code/demo/testBufferedWriter.txt"));

for(String line:lines)System.out.println("Files.readAllLines=="+line);

try(BufferedWriter bw = Files.newBufferedWriter(Paths.get("/Users/buxuesong/Documents/svn_code/demo/testNewBufferedWriter.txt"))){
    for(String d:data){
        bw.write(d);
        bw.newLine();

    }
}

Zip压缩文件写法:

public class ZipFileTest {

    public static void main(String args[]){

        String[] data ={
                "Line 1",
                "Line 2 2",
                "Line 3 3 3",
                "Line 4 4 4 4",
                "Line 5 5 5 5 5"
        };
        try(FileSystem zipFs = openZip(Paths.get("/Users/buxuesong/Documents/svn_code/demo/myData.zip"))){
            copyToZip(zipFs);
            writeToFileInZip1(zipFs,data);
            writeToFileInZip2(zipFs,data);
        }catch (Exception e){
            System.out.println(e.getClass().getSimpleName()+"-"+e.getMessage());
        }
    }

    private static FileSystem openZip(Path zipPath) throws IOException,URISyntaxException {
        Map providerProps = new HashMap<>();
        providerProps.put("create","true");
        URI zipUri = new URI("jar:file",zipPath.toUri().getPath(),null);
        FileSystem zipFs = FileSystems.newFileSystem(zipUri, providerProps);
        return zipFs;
    }

    private static void copyToZip(FileSystem zipFs) throws IOException{
        Path sourceFile = Paths.get("/Users/buxuesong/Documents/svn_code/demo/test.txt");
//        Path sourceFile =  .getDefault().getPath("/Users/buxuesong/Documents/svn_code/demo/test.txt");
        Path destFile = zipFs.getPath("/file1Copied.txt");

        Files.copy(sourceFile,destFile, StandardCopyOption.REPLACE_EXISTING);
    }

    private static void writeToFileInZip1(FileSystem zipFs, String[] data) throws IOException{
        try(BufferedWriter bw = Files.newBufferedWriter(zipFs.getPath("/newFile1.txt"))){
            for(String d:data){
                bw.write(d);
                bw.newLine();
            }
        }
    }
    private static void writeToFileInZip2(FileSystem zipFs, String[] data) throws IOException{
       Files.write(zipFs.getPath("/newFile2.txt"), Arrays.asList(data),
               Charset.defaultCharset(), StandardOpenOption.CREATE);
    }
}

Writer
output类型
Disk:FileWrite
In-Memory:CharArrayWriter
StringWriter, 写入StringBuffer
行为类型:
BufferedWriter
PrintWriter

StandardOpenOption类型
WRITE,APPEND写入
CREATE,CREATE_NEW,创建,创建新的
DELETE_ON_CLOSE,完成后删除(临时文件)

try(BufferedWriter bw = Files.newBufferedWriter(
        Paths.get("/Users/buxuesong/Documents/svn_code/test.txt")
        ,StandardOpenOption.CREATE,StandardOpenOption.WRITE)){
    PrintWriter pw = new PrintWriter(bw);
    pw.write("Hello World!\n");
    pw.printf("W:%4d X:%4d\n",5,235);
    Calendar cl = Calendar.getInstance();
    cl.set(1987,11,23);
    pw.printf(Locale.US,"I birthed on %1$tB %1$tA %1$tY",cl);
}catch (IOException e){
}
//输出文件
Hello World!
W:   5 X: 235
I birthed on December Wednesday 1987

Reader方法

//关闭流并释放与其关联的所有系统资源。
abstract void    close()    
//标记流中的当前位置。
void    mark(int readAheadLimit)    
//判断此流是否支持mark()操作。
boolean    markSupported()    
//返回不读取任何字符的新 Reader 。
static Reader    nullReader()    
//读一个字符。
int    read()    
//将字符读入数组。
int    read(char[] cbuf)    
//将字符读入数组的一部分。
abstract int    read(char[] cbuf, int off, int len)    
//尝试将字符读入指定的字符缓冲区。
int    read(CharBuffer target)    
//判断此流是否可以读取。
boolean    ready()    
//重置流。
void    reset()    
//跳过字符。
long    skip(long n)    
//读取此阅读器中的所有字符,并按照读取的顺序将字符写入给定的编写器。
long    transferTo(Writer out)    

DataOutputSteam & DataInputStream

public static void main(String[] args) {
    try(OutputStream out = Files.newOutputStream(Paths.get("C:\\Users\\Xuesong.Bu\\Desktop\\a.txt"))){
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeInt(1);
        dos.writeLong(2222L);
        dos.writeDouble(1.23);
        dos.writeChar('H');
        dos.writeUTF("hha");
    }catch (Exception e){
        e.printStackTrace();
    }
    try(InputStream in = Files.newInputStream(Paths.get("C:\\Users\\Xuesong.Bu\\Desktop\\a.txt"))){
        DataInputStream dis = new DataInputStream(in);
        int a = dis.readInt();
        System.out.println(a);
        Long b = dis.readLong();
        System.out.println(b);
        Double c = dis.readDouble();
        System.out.println(c);
        char d = dis.readChar();
        System.out.println(d);
        String e = dis.readUTF();
        System.out.println(e);
    }catch (Exception e){
        e.printStackTrace();
    }
}
//输出
1
2222
1.23
H
hha

Files循环读取文件夹下子目录及文件

Path path = Paths.get("/Users/buxuesong/Documents");

FileVisitor fileVisitor = new FileVisitor(){
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        fileCount ++;
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }
};
Files.walkFileTree(path, fileVisitor);
System.out.println(fileCount);

//另外几种循环读取所有文件个数
Path path = Paths.get("/Users/buxuesong/Documents/python-learn/ch01");
Stream stream = Files.walk(path);
System.out.println(Files.walk(path)
        .filter(Files::isDirectory)
        .count());
System.out.println(Files.walk(path)
        .filter(Files::isRegularFile)
        .count());
System.out.println(stream.count());

你可能感兴趣的:(JAVA基础之文件流输入输出)