JAVA中的IO

Wesley13
• 阅读 481

FILE类常量

import java.io.*;  
class hello{  
    public static void main(String[] args) {  
        System.out.println(File.separator);//输出"/"
        System.out.println(File.separatorChar + "");//输出"/"
        System.out.println(File.pathSeparator);//输出 ":"
        System.out.println(File.pathSeparatorChar + "");//输出 ":"
   }
}

在windows下使用\进行分割,但是在linux下就不是\了。所以,要想使得我们的代码跨平台,更加健壮,所以,采用这两个常量吧

创建文件

import java.io.*;  
class hello{  
    public static void main(String[] args) {  
        File f=new File("D:\\hello.txt");  
        try{  
            f.createNewFile();  
        }catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}

创建一个文件夹

import java.io.*;  
class hello{  
    public static void main(String[] args) {  
        String fileName="D:"+File.separator+"hello";  
        File f=new File(fileName);  
        f.mkdir();  
    }  
}

删除一个文件

import java.io.*;  
class hello{  
    public static void main(String[] args) {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        if(f.exists()){  
            f.delete();  
        }else{  
            System.out.println("文件不存在");  
        } 
    }  
}

列出指定目录的全部文件名(包括隐藏文件)

/**  
 * 使用list列出指定目录的全部文件名  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) {  
        String fileName="D:"+File.separator;  
        File f=new File(fileName);  
        String[] str=f.list();  
        for (int i = 0; i < str.length; i++) {  
            System.out.println(str[i]);  
        }  
    }  
}

列出指定目录的全部文件(包括隐藏文件)

/**  
 * 使用listFiles列出指定目录的全部文件  
 * listFiles输出的是完整路径  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) {  
        String fileName="D:"+File.separator;  
        File f=new File(fileName);  
        File[] str=f.listFiles();  
        for (int i = 0; i < str.length; i++) {  
            System.out.println(str[i]);  
        }  
    }  
}

判断一个指定的路径是否为目录

/**  
 * 使用isDirectory判断一个指定的路径是否为目录  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) {  
        String fileName="D:"+File.separator;  
        File f=new File(fileName);  
        if(f.isDirectory()){  
            System.out.println("YES");  
        }else{  
            System.out.println("NO");  
        }  
    }  
}

搜索指定目录的全部内容

/**  
 * 列出指定目录的全部内容  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) {  
        String fileName="D:"+File.separator;  
        File f=new File(fileName);  
        print(f);  
    }  
    public static void print(File f){  
        if(f!=null){  
            if(f.isDirectory()){  
                File[] fileArray=f.listFiles();  
                if(fileArray!=null){  
                    for (int i = 0; i < fileArray.length; i++) {  
                        //递归调用  
                        print(fileArray[i]);  
                    }  
                }  
            }  
            else{  
                System.out.println(f);  
            }  
        }  
    }  
}

使用RandomAccessFile写入文件

/**  
 * 使用RandomAccessFile写入文件  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        RandomAccessFile demo=new RandomAccessFile(f,"rw");  
        demo.writeBytes("asdsad");  
        demo.writeInt(12);  
        demo.writeBoolean(true);  
        demo.writeChar('A');  
        demo.writeFloat(1.21f);  
        demo.writeDouble(12.123);  
        demo.close();     
    }  
}

中文乱码,不能对文件进行覆写不能追加

向文件中写入字符串

/**  
 * 字节流  
 * 向文件中写入字符串  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        OutputStream out =new FileOutputStream(f);  
        String str="你好";  
        byte[] b=str.getBytes();  
        out.write(b);  
        out.close();  
    }  
}

中文不乱码,文件不存在会创建,会覆写

一个字节一个字节的写

/**  
 * 字节流  
 * 向文件中一个字节一个字节的写入字符串  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        OutputStream out =new FileOutputStream(f);  
        String str="你好";  
        byte[] b=str.getBytes();  
        for (int i = 0; i < b.length; i++) {  
            out.write(b[i]);  
        }  
        out.close();  
    }  
}

向文件中追加新内容

/**  
 * 字节流  
 * 向文件中追加新内容:  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        OutputStream out =new FileOutputStream(f,true);//追加模式  
        String str="Rollen";  
        //String str="\r\nRollen";  可以换行  
        byte[] b=str.getBytes();  
        for (int i = 0; i < b.length; i++) {  
            out.write(b[i]);  
        }  
        out.close();  
    }  
}

读取文件内容

/**  
 * 字节流  
 * 读文件内容  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        InputStream in=new FileInputStream(f);  
        byte[] b=new byte[1024];  
        in.read(b);  
        in.close();  
        System.out.println(new String(b));  
    }  
}

创建合适长度的空间大小

/**  
 * 字节流  
 * 读文件内容,节省空间  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        InputStream in=new FileInputStream(f);  
        byte[] b=new byte[(int)f.length()];  
        in.read(b);  
        System.out.println("文件长度为:"+f.length());  
        in.close();  
        System.out.println(new String(b));  
    }  
}

一个一个读

/**  
 * 字节流  
 * 读文件内容,节省空间  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        InputStream in=new FileInputStream(f);  
        byte[] b=new byte[(int)f.length()];  
        for (int i = 0; i < b.length; i++) {  
            b[i]=(byte)in.read();  
        }  
        in.close();  
        System.out.println(new String(b));  
    }  
}

文件不知道长度读取

/**  
 * 字节流  
 *读文件  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        InputStream in=new FileInputStream(f);  
        byte[] b=new byte[1024];  
        int count =0;  
        int temp=0;  
        while((temp=in.read())!=(-1)){//返回-1则表示到了文件尾部
            b[count++]=(byte)temp;  
        }  
        in.close();  
        System.out.println(new String(b));  
    }  
}

字符流写入数据

/**  
 * 字符流  
 * 写入数据  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        Writer out =new FileWriter(f);//追加时和上面一样加一为true的参数
        String str="hello";  
        out.write(str);  
        out.close();  
    }  
}

字符流从文件中读出内容

/**  
 * 字符流  
 * 从文件中读出内容  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        char[] ch=new char[100];  
        Reader read=new FileReader(f);  
        int count=read.read(ch);  
        read.close();  
        System.out.println("读入的长度为:"+count);  
        System.out.println("内容为"+new String(ch,0,count));  
    }  
}

循环读取的方式

/**  
 * 字符流  
 * 从文件中读出内容  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName="D:"+File.separator+"hello.txt";  
        File f=new File(fileName);  
        char[] ch=new char[100];  
        Reader read=new FileReader(f);  
        int temp=0;  
        int count=0;  
        while((temp=read.read())!=(-1)){  
            ch[count++]=(char)temp;  
        }  
        read.close();  
        System.out.println("内容为"+new String(ch,0,count));  
    }  
}

OutputStreramWriter将输出的字符流转化为字节流
InputStreamReader将输入的字节流转换为字符流

将字节输出流转化为字符输出流

/**  
 * 将字节输出流转化为字符输出流  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName= "d:"+File.separator+"hello.txt";  
        File file=new File(fileName);  
        Writer out=new OutputStreamWriter(new FileOutputStream(file));  
        out.write("hello");  
        out.close();  
    }  
}

将字节输入流变为字符输入流

/**  
 * 将字节输入流变为字符输入流  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String fileName= "d:"+File.separator+"hello.txt";  
        File file=new File(fileName);  
        Reader read=new InputStreamReader(new FileInputStream(file));  
        char[] b=new char[100];  
        int len=read.read(b);  
        System.out.println(new String(b,0,len));  
        read.close();  
    }  
}

ByteArrayInputStream 主要将内容写入内容
ByteArrayOutputStream 主要将内容从内存输出

使用内存操作流将一个大写字母转化为小写字母

/**  
 * 使用内存操作流将一个大写字母转化为小写字母  
 * */ 
import java.io.*;  
class hello{  
    public static void main(String[] args) throws IOException {  
        String str="ROLLENHOLT";  
        ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());  
        ByteArrayOutputStream output=new ByteArrayOutputStream();  
        int temp=0;  
        while((temp=input.read())!=-1){  
            char ch=(char)temp;  
            output.write(Character.toLowerCase(ch));  
        }  
        String outStr=output.toString();  
        input.close();  
        output.close();  
        System.out.println(outStr);  
    }  
}

内容操作流一般使用来生成一些临时信息采用的,这样可以避免删除的麻烦。

版权声明:本文为博主原创文章,未经博主允许不得转载。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java日期时间API系列31
  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这