输入和输出处理(一)IO

File类:
绝对路径:从根目录开始找,找到文件经过的路径
相对路径:从当前目录开始,找到文件经过的路径
与Windows操作文件和文件夹基本一致、权限为读写执行三种
主要操作为:文件夹和文件的增删改查
流:流是个抽象的概念,是对输入输出设备的抽象,Java程序中,
对于数据的输入/输出操作都是以“流”的方式进行。设备可以是文件,网络,内存等。
流分类:
按流向分:输出流OutputStream和Writer作为基类
                输入流InputStream和Reader作为基类
按处理数据单元划分:字节流:输入流:InputStream基类;
            输出流:OutputStream基类
        字符流:输入流:Reader基类
            输出流:Writer基类
File常用方法:
boolean exists( )  判断文件或目录是否存在
boolean isFile( )   判断是否是文件
boolean isDirectory( )  判断是否是目录
String getPath( )返回此对象表示的文件的相对路径名
String getAbsolutePath( )返回此对象表示的文件的绝对路径名
String getName( )返回此对象表示的文件或目录的名称
boolean delete( )删除此对象指定的文件或目录
boolean createNewFile( )创建名称的空文件,不创建文件夹
long  length()返回文件的长度,单位为字节, 如果文件不存在,则返回 0L
InputStream类常用方法
int read( )
int read(byte[] b)
int read(byte[] b,int off,int len)
void close( )
int available():可以从输入流中读取的字节数目
子类FileInputStream常用的构造方法
 FileInputStream(File file)
FileInputStream(String name)

OutputStream类常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close()
void flush():强制把缓冲区的数据写到输出流中

FileOutputStream常用的构造方法
FileOutputStream (File file)
FileOutputStream(String name)    
FileOutputStream(String name,boolean append)
流的使用:

文件路径要使用File对象进行合法性判断
输入流如果是字节型,尽量不要有的中文字符
输出流可以有替换和追加两种模式,在fos的构造器的第二个参数填入true
关闭流

创建文件
public void read(){
        //创建文件
        File file=new File("路径");
        File f=file.getParentFile();
        if (!f.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(file.getAbsolutePath());
        }
    }
   public void readFile(String path) throws IOException{
        File file=new File(path);
        StringBuilder sb=new StringBuilder();
        FileInputStream fis=new FileInputStream(file);
        if (!file.exists()){
            throw new IOException("文件不存在");
        }
        while (fis.available()>0){
            sb.append((char)fis.read());
            String str=new String(sb);
            System.out.println(str);
        }
       
       }
       public void writeFile(String path,String s) throws IOException{
        File file=new File(path);
        FileOutputStream fos=new FileOutputStream(file);
        if (s==null){
            return;
        }for (int i=0;i<s.length();i++){
            fos.write(s.charAt(i));
           }
           fos.close();//这里的S表示字符串,可以传入进来。例如在上面的我把文件内容读取后,加入到"sb"中,
           //我又就进行操作String str=new String(sb);System.out.println(str);
           这样我就可以把相关数据转成String型,这样就可以调用很多String的方法。
        
       }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值