io流

复制文件的三种方法

//复制文件1 最简单的一种
//用到的java类: FileInputStream,FileOutputStream
//用到的方法: read(),write() public static void main(String[] args) throws IOException { FileInputStream fis=new FileInputStream("D:\pic2.jpg"); FileOutputStream fos=new FileOutputStream("D:\pic3.jpg"); byte[] bytes=new byte[1024]; int len=0; while( (len=fis.read(bytes))!=-1 ){   fos.write(bytes, 0, len); } fos.close(); fis.close(); } //复制文件2
//用到的java类: FileInputStream,FileOutputStream,BufferedInputStream,BufferedOutputStream
//用到的方法: read(),write() public static void main(String[] args) throws IOException { FileInputStream fis=new FileInputStream("D:\pic3.jpg"); FileOutputStream fos=new FileOutputStream("D:\pic4.jpg"); BufferedInputStream bis=new BufferedInputStream(fis); BufferedOutputStream bos=new BufferedOutputStream(fos); byte[] bytes=new byte[1024]; int len=0; while( (len=bis.read(bytes))!=-1 ){ bos.write(bytes,0, len); } bos.close(); bis.close(); fos.close(); fis.close(); System.out.println("finish"); }
//复制文件3   
//用到的java类: FileInputStream,FileOutputStream,FileChannel,ByteBuffer 
//用到的方法 getChannel(),ByteBuffer.allcate(1024),read(),flip(),write(),clear()
public static void main(String[] args) throws IOException {
        
        //创建io流
        FileInputStream fis=new FileInputStream("D:\pic4.jpg");
        FileOutputStream fos=new FileOutputStream("D:\pic5.jpg");
        //得到通道 用通道对象进行读和写操作
        FileChannel inputchannel=fis.getChannel();
        FileChannel outputChannel=fos.getChannel();
        //创建字节缓冲区ByteBuffer  每一个基本数据类型都有一个缓冲区Buffer
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        //判断返回值是否read读取成功
        int len=0;
        //用输入流的通道的读取数据read方法 参数是缓冲区对象 返回-1的话就是没有数据可读取 停止循环
        while((len=inputchannel.read(byteBuffer))!=-1){
            //读写转换flip()
            byteBuffer.flip();
            //用输出流的通道写入数据 参数是缓冲区对象
            outputChannel.write(byteBuffer);
            //清空缓冲区数据   进行下一次循环才有空间把数据读到缓冲区里
            byteBuffer.clear();
        }
        System.out.println("finish");
        //按后开先关的顺序关闭流和通道
        outputChannel.close();
        fos.close();
        inputchannel.close();
        fis.close();
        
}

string,stringbuffer,stringbuilder的区别

string 字符串常量 不会对本身数据进行修改 而是每次修改都会new一个新的string对象接收 效率低 

先定义一个字符串常量后 用同名接收 实际上第二个是新new出来的对象  那么第一行的string字符串就会被gc当垃圾回收

1 String s = "abcd";
2 s = s+1;
3 System.out.print(s);// result : abcd1

StringBuilder与 StringBuffer

    StringBuilder:线程非安全的

    StringBuffer:线程安全的

    当我们在字符串缓冲去被多个线程使用是,JVM不能保证StringBuilder的操作是安全的,虽然他的速度最快,但是可以保证StringBuffer是可以正确操作的。当然大多数情况下就是我们是在单线程下进行的操作,所以大多数情况下是建议用StringBuilder而不用StringBuffer的,就是速度的原因。

           对于三者使用的总结: 1.如果要操作少量的数据用 = String

                        2.单线程操作字符串缓冲区 下操作大量数据 = StringBuilder

                        3.多线程操作字符串缓冲区 下操作大量数据 = StringBuffer

  

原文地址:https://www.cnblogs.com/m97i/p/7731825.html