File 类,InputStream, OutputStream 的用法

目录

一.File类

关于名字和路径的操作

关于创建和销毁的操作

创建文件夹(多级目录)

 InputStream

第一种:字节流读取

第二种: 字符流读取(Reader)

 OutputStream 

第一种:字节流写入

 第二种方式:字符流输入


一.File类

File翻译过来"文件"

那么File类的操作实际上就全部是对文件进行操作

关于名字和路径的操作

    public static void main(String[] args) {
//虚拟一个名字叫做test.txt的文件,但这一步只是虚拟的,还没有创建
        File file = new File("./test.txt");
        System.out.println(file.getParent());//获取这个文件的父目录的路径
        System.out.println(file.getName());//获取这个文件的名字
        System.out.println(file.getPath());//获取这个文件的相对路径
        System.out.println(file.getAbsolutePath());//获取这个文件的绝对路径
    }

关于创建和销毁的操作

    public static void main(String[] args) throws IOException {
//拟创建一个叫做Test.txt的文件,但还没创建
        File file = new File("./Test.txt");
//真的在计算机的当前目录创建了这个文件
        file.createNewFile();
        System.out.println(file.isFile());//判断是否是普通文件
        System.out.println(file.isDirectory());//判断是否是目录文件
        System.out.println(file.exists());//判断这个文件是否存在
        System.out.println(file.delete());//删除这个文件
        System.out.println(file.exists());
    }

创建文件夹(多级目录)

    public static void main(String[] args) {
        File file = new File("./hello1");
        File file2 = new File("./hello2/6666");
        file.mkdir();//只能创建一级目录
        file2.mkdirs();//能创建多级目录
    }

 InputStream

就是从文件里面读取数据

一般有两种读取方式

第一种:字节流读取

(读写的基本单位是字节)

基本方法: read() :读取一个字节的数据,返回-1代表读取完毕

使用

我们先在D盘创建一个名字叫做hello.txt的文件,然后输入hello

 

    public static void main(String[] args) throws FileNotFoundException {
        InputStream inputStream = new FileInputStream("D:/hello.txt");//这里输入读取的文件地址,如果输入错误会报错无法读取
        while(true){
            try {
                int ret = inputStream.read();//如果全部读取完毕返回-1
                if(ret == -1){
                    break;
                }
                System.out.println(ret);

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

输出的为对应的ASCII码~

 

第二种: 字符流读取(Reader)

运行原理和字节流读取一样,唯一不同的是在屏幕上显示的是字符而不是ask表对应的数字

    public static void main(String[] args) throws FileNotFoundException {
        Reader reader = new FileReader("D:/hello.txt");
        while(true){
            try {
                int ret = reader.read();
                if(ret == -1){
                    break;
                }
                System.out.println((char)ret);

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

 OutputStream 

就是向文件里面写数据

一般有两种写入方式

第一种:字节流写入

基本方法: write() 

    public static void main(String[] args) throws FileNotFoundException {
        OutputStream outputStream = new FileOutputStream("d:/hello.txt");
        try {
//注意,这里的98,99,100是ask码表对应的数字的字符,不是数字98,99,100
            outputStream.write(98);
            outputStream.write(99);
            outputStream.write(100);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

 第二种方式:字符流输入

这种方式一定要注意在最后使用flush方式

把存储在内存中的字节流拿出来

否则会什么都没有但是程序依然不报错

    public static void main(String[] args) throws IOException {
        Writer writer = new FileWriter("d:/hello2.txt");
        writer.write("hello");
//一定要加上flush!!!!!
//一定要加上flush!!!!!
//一定要加上flush!!!!!
        writer.flush();
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
android Bitmap用法总结 Bitmap用法总结 1、Drawable → Bitmap public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); // canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } 2、从资源中获取Bitmap Resources res=getResources(); Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic); 3、Bitmap → byte[] private byte[] Bitmap2Bytes(Bitmap bm){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } 4、byte[] → Bitmap private Bitmap Bytes2Bimap(byte[] b){ if(b.length!=0){ return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } } 5、保存bitmap static boolean saveBitmap2file(Bitmap bmp,String filename){ CompressFormat format= Bitmap.CompressFormat.JPEG; int quality = 100; OutputStream stream = null; try { stream = new FileOutputStream("/sdcard/" + filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. e.printStackTrace(); } return bmp.compress(format, quality, stream); } 6、将图片按自己的要求缩放 // 图片源 Bitmap bm = BitmapFactory.decodeStream(getResources() .openRawResource(R.drawable.dog)); // 获得图片的宽高 int width = bm.getWidth(); int height = bm.getHeight(); // 设置想要的大小 int newWidth = 320; int newHeight = 480; // 计算缩放比例 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 取得想要缩放的matrix参数 Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // 得到新的图片 Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true); // 放在画布上 canvas.drawBitmap(newbm, 0, 0, paint); 相关知识链接:http://www.eoeandroid.com/thread-3162-1-1.html 7、bitmap的用法小结 BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = 2; //将图片设为原来宽高的1/2,防止内存溢出 Bitmap bm = BitmapFactory.decodeFile("",option);//文件流 URL url = new URL(""); InputStream is = url.openStream(); Bitmap bm = BitmapFactory.decodeStream(is); android:scaleType: android:scaleType是控制图片如何resized/moved来匹对ImageView的size。ImageView.ScaleType / android:scaleType值的意义区别: CENTER /center 按图片的原来size居中显示,当图片长/宽超过View的长/宽,则截取图片的居中部分 显示 CENTER_CROP / centerCrop 按比例扩大图片的size居中显示,使得图片长(宽)等于或大于View的长 (宽) CENTER_INSIDE / centerInside 将图片的内容完整居中显示,通过按比例缩小或原来的size使得图片 长/宽等于或小于View的长/宽 Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. FIT_CENTER / fitCenter 把图片按比例扩大/缩小到View的宽度,居中显示 FIT_END / fitEnd 把图片按比例扩大/缩小到View的宽度,显示在View的下部分位置 FIT_START / fitStart 把图片按比例扩大/缩小到View的宽度,显示在View的上部分位置 FIT_XY / fitXY 把图片 不按比例 扩大/缩小到View的大小显示 MATRIX / matrix 用矩阵来绘制,动态缩小放大图片来显示。 //放大缩小图片 public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){ int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidht = ((float)w / width); float scaleHeight = ((float)h / height); matrix.postScale(scaleWidht, scaleHeight); Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); return newbmp; } //将Drawable转化为Bitmap public static Bitmap drawableToBitmap(Drawable drawable){ int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0,0,width,height); drawable.draw(canvas); return bitmap; Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. } //获得圆角图片的方法 public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){ Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap .getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } //获得带倒影的图片方法 public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap){ final int reflectionGap = 4; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height/2, width, height/2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(bitmap, 0, 0, null); Paint deafalutPaint = new Paint(); Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. canvas.drawRect(0, height,width,height + reflectionGap, deafalutPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); // Set the Transfer mode to be porter duff and destination in paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // Draw a rectangle using the paint with our linear gradient canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } }
Java 基础核心总结》 Java 概述 什么是 Java2 Java 的特点Java 开发环境 JDK JRE Java 开发环境配置 Java 基本语法 数据型基础语法运算符 Java 执行控制流程条件语句 if 条件语句 if...else 条件语句if...else if 多分支语句switch 多分支语句 循环语句 while 循环语句do...while 循环for 循环语句 跳转语句 break 语句 continue 语句面向对象 也是-种对象对象的创建 属性和方法 构造方法 方法重载 方法的重写 初始化 的初始化 成员初始化 构造器初始化初始化顺序 数组初始化 对象的销毁 对象作用域 this 和 super 访问控制权限继承 多态组合代理 向上转型static final 接口和抽象接口 抽象异常 认 识 Exception 什么是 Throwable 常见的 Exception 与 Exception 有关的 Java 关键字 throws 和 throw try 、finally 、catch 什么是 Error 内部 创建内部集合 Iterable 接口顶层接口 ArrayList Vector LinkedList Stack HashSet TreeSet LinkedHashSet PriorityQueue HashMap TreeMap LinkedHashMap Hashtable IdentityHashMap WeakHashMap Collections 集合实现特征图 泛形 泛型的使用 用泛型表示 用泛型表示接口泛型方法 泛型通配符 反射 Class Field Method ClassLoader 枚举 枚举特性 枚举和普通-样枚举神秘之处 枚举 I/O File 基础 IO 和相关方法InputStream OutputStream Reader Writer InputStream 及其子 OutputStream 及其子Reader 及其子Writer 及其子 注解 关于 null 的几种处理方式大小写敏感 null 是任何引用型的初始值 null 只是-种特殊的值使用 Null-Safe 方法null 判断 关于思维导图 Java.IO Java.lang Java.math Java.net Java 基础核心总结 V2.0 IO 传统的 BIO BIO NIO 和 AIO 的区别什么是流 流的分 节点流和处理流 Java IO 的核心 File Java IO 流对象 字节流对象InputStream OutputStream 字符流对象Reader Writer 字节流与字符流的转换新潮的 NIO 缓冲区(Buffer)通道(Channel) 示例:文件拷贝案例 BIO 和 NIO 拷贝文件的区别操作系统的零拷贝 选择器(Selectors) 选择键(SelectionKey) 示例:简易的客户端服务器通信 集合 集合框架总览 -、Iterator Iterable ListIterator 二、Map 和 Collection 接口Map 集合体系详解 HashMap LinkedHashMap TreeMap WeakHashMap Hashtable Collection 集合体系详解 Set 接口 AbstractSet 抽象SortedSet 接口HashSet LinkedHashSet TreeSet List 接口 AbstractList 和 AbstractSequentialList Vector Stack ArrayList LinkedList Queue接口Deque 接口 AbstractQueue 抽象LinkedList ArrayDeque PriorityQueue 反射的思想及作用 反射的基本使用 获取的 Class 对象构造的实例化对象获取-个的所有信息 获取中的变量(Field) 获取中的方法(Method) 获取的构造器(Constructor) 获取注解 通过反射调用方法反射的应用场景 Spring 的 IOC 容器反射 + 抽象工厂模式 JDBC 加载数据库驱动反射的优势及缺陷 增加程序的灵活性破坏的封装性 性能损耗 代理模式 静态代理与动态代理常见的动态代理实现JDK Proxy CGLIB JDK Proxy 和 CGLIB 的对比动态代理的实际应用 Spring AOP 变量 变量汇总实例变量 实例变量的特点全局变量 静态变量 静态变量的特点变量 局部变量
Java中,inputstreamoutputstream是常用于文件操作的Inputstream是用来读取文件数据的,Outputstream则是用来写入文件数据的。File则是用来表示文件或目录的抽象表示。 要实现inputstreamoutputstreamfile间的互转,需要使用Java IO中的一些方法。其中,FileInputStreamFileOutputStream用于将文件与inputstreamoutputstream进行互转换。FileReader和FileWriter用于将字符数据与inputstreamoutputstream进行互转换。另外,ByteArrayInputStream和ByteArrayOutputStream用于在内存中进行数据流操作。 以FileInputStreamFileOutputStream为例,可以通过以下步骤实现inputstreamfileoutputstream间的转换: 1.创建一个FileInputStream对象,将要读取的文件传递给构造函数。 2.通过read()方法读取文件中的数据。 3.创建一个FileOutputStream对象,将要写入的文件传递给构造函数。 4.通过write()方法将读取到的数据写入到输出流中。 以下是代码示例: ``` import java.io.*; public class FileOperation { public static void main(String args[]) { try { //创建一个输入流 FileInputStream in = new FileInputStream("input.txt"); // 读取第一个字节 int c = in.read(); while(c != -1) { System.out.print((char)c); //读取下一个字节 c = in.read(); } //关闭输入流 in.close(); //创建输出流 FileOutputStream out =new FileOutputStream("output.txt"); //写入数据 String str = "Hello Java Programming!"; byte[] bytes = str.getBytes(); out.write(bytes); //关闭输出流 out.close(); } catch (IOException e) { System.out.println("IOException"); } } } ``` 在上面的示例中,程序首先通过FileInputStream读取了一个文件的内容,然后通过FileOutputStream将读取到的内容写入到了另一个文件中。 总之,通过Java IO的各种操作,可以很方便地实现inputstreamoutputstreamfile间的互转。这些方法在读写文件、网络编程等方面都有广泛应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值