Java 文件帮助类


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 文件帮助类
 */
@Slf4j
public class FileUtils {

    /**
     * 复制文件并输入文件
     * @param : @param filePath1 原文件
     * @param : @param filePath2 复制之后的文件
     */
    public static void copyFile(String filePath1, String filePath2) {
        // 读取本地文件
        try (FileInputStream in = new FileInputStream(filePath1);
            // 创建新的输出文件类
            FileOutputStream out = new FileOutputStream(filePath2)){
            byte[] b = new byte[1024];
            while (in.read(b) > -1) {
                out.write(b);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 文件转成byte[]
     * @param : @param filePath
     * @param : @return
     * @return: byte[]
     */
    public static byte[] getBytesByFile(String filePath) {
        byte[] data = null;
        // 创建文件类
        File file = new File(filePath);
        try (FileInputStream fis = new FileInputStream(file);
            // 字节输出流,其中数据被写入到字节数组中
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000)) {

            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            data = bos.toByteArray();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return data;
    }

    /**
     * 文件转成byte[]
     * @param : @param file
     * @param : @return
     * @return: byte[]
     */
    public static byte[] getBytesByFile(File file) {
        byte[] data = null;
        try (FileInputStream fis = new FileInputStream(file);
            // 字节输出流,其中数据被写入到字节数组中
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000)) {

            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            data = bos.toByteArray();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return data;
    }


    /**
     * 将byte数组转换成文件
     * @param : @param bytes
     * @param : @param filePath
     * @param : @param fileName
     */
    public static void writeFileByBytes(byte[] bytes, String filePath, String fileName) {
        // 检查路径是否存在,创建file文件
        File file = new File(ExistsPathUtils.exists(filePath), fileName);
        try (InputStream is = new ByteArrayInputStream(bytes);
            OutputStream os = new FileOutputStream(file)) {

            // 每次传10M, 断点续传, 否则内存溢出; 如果一味的调整JVM的大小,治标不治本
            byte[] byteStr = new byte[1024 * 1024 * 10];
            int len = 0;

            while ((len = is.read(byteStr)) > 0) {
                os.write(byteStr,0,len);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }


    /**
     * 把某个文件写到指定地址
     * @param : @param file 文件
     * @param : @param filePath 写入地址
     */
    public static void writeFile(File file, String filePath) {
        byte[] b = getBytesByFile(file);
        try (FileOutputStream outputStream = new FileOutputStream(filePath)){
            outputStream.write(b);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 获取网络图片流
     **/
    public static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            log.error("获取网络图片出现异常,图片路径为:" + url);
            log.error(e.getMessage());
        }
        return null;
    }

    // 静态帮组类
    private static class ExistsPathUtils {
        // 判断文件是否存在
        public static File exists(String filePath) {
            File disk = new File(filePath);
            // 如果路径不存在就创建
            if (!disk.exists()) disk.mkdirs();
            return disk;
        }
    }
}

常用的io包,还有一个lombok包

 
Java Platform Standard Edition 7 Documentation What's New Documentation Release Notes Tutorials and Training The Java Tutorials Java Training More Information Java SE 7 Names and Versions Java SE White Papers Documentation Accessibility Specifications Installation Instructions Supported Systems Configurations Java SE 7 and JDK 7 Compatibility JDK 7 Adoption Guide Troubleshooting Java SE About Test / Sample Applications and Code Resources Oracle Java SE Advanced and Oracle Java SE Suite Open JDK Bugs Database Downloads Java SE Downloads Community Forums Blogs User Groups Wikis Newsletters Events Other Technologies Java EE Java ME Java FX GlassFish NetBeans Oracle has two products that implement Java Platform Standard Edition (Java SE) 7: Java SE Development Kit (JDK) 7 and Java SE Runtime Environment (JRE) 7. JDK 7 is a superset of JRE 7, and contains everything that is in JRE 7, plus tools such as the compilers and debuggers necessary for developing applets and applications. JRE 7 provides the libraries, the Java Virtual Machine (JVM), and other components to run applets and applications written in the Java programming language. The following conceptual diagram illustrates Java component technologies: JDK Java Language Java Language ` Tools & Tool APIs java javac javadoc jar javap JPDA JConsole Java VisualVM Java DB Security Int'l RMI IDL Deploy Monitoring Troubleshoot Scripting JVM TI JRE RIAs Java Web Start Applet / Java Plug-in User Interface Toolkits AWT Swing Java 2D Accessibility Drag n Drop Input Methods Image I/O Print Service Sound Java SE API Integration Libraries IDL JDBC JNDI RMI RMI-IIOP Scripting Other Base Libraries Beans Int'l Support Input/Output JMX JNI Math Networking Override Mechanism Security Serialization Extension Mechanism XML JAXP lang and util Base Libraries lang and util Collections Concurrency Utilities JAR Logging Management Preferences API Ref Objects Reflection Regular Expressions Versioning Zip Instrumentation Java Virtual Machine Java HotSpot Client and Server VM Description of Java Conceptual Diagram What's New in Documentation Documentation is regularly updated to provide developers with in-depth information about new features in the Java platform. Some recent updates include: Swing The JLayer class has been added, which is a flexible and powerful decorator for Swing components; see How to Decorate Components with JLayer. The Nimbus Look and Feel has been moved from the com.sun.java.swing package to the javax.swing package; see the javax.swing.plaf.nimbus package. Mixing Heavyweight and Lightweight Components is easier to accomplish. Windows with transparency and non-rectangular shape are supported; see How to Create Translucent and Shaped Windows An HSV tab has been added to the JColorChooser class. Java I/O The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system; see File I/O (featuring NIO.2). NIO stands for non-blocking I/O. The directory <Java home>/sample/nio/chatserver/ contains samples that demonstrate the new APIs contained in the java.nio.file package. The directory <Java home>/demo/nio/zipfs/ contains samples that demonstrate the NIO.2 NFS (Network File System) file system. Networking The URLClassLoader.close method has been added; see Closing a URLClassLoader. The Sockets Direct Protocol (SDP) provides access to high performance network connections; see Understanding the Sockets Direct Protocol. Security A new native provider has been added that provides several ECC-based algorithms (ECDSA/ECDH); see Sun PKCS#11 Provider's Supported Algorithms in Java PKCS#11 Reference Guide. Weak cryptographic algorithms can now be disabled; see Appendix D: Disabling Cryptographic Algorithms in Java PKI Programmer's Guide and Disabled Cryptographic Algorithms in Java Secure Socket Extension (JSSE) Reference Guide. Various enhancements related to SSL/TLS have been added to Java Secure Socket Extension. Collections The TransferQueue interface has been added, which is a refinement of the BlockingQueue interface. The class LinkedTransferQueue implements the TransferQueue interface. Concurrency The fork/join framework, which is based on the ForkJoinPool class, is an implementation of the Executor interface. It is designed to efficiently run a large number of tasks using a pool of worker threads. A work-stealing technique is used to keep all the worker threads busy, to take full advantage of multiple processors. See Fork/Join in The Java Tutorials. The directory <Java home>/sample/forkjoin/ contains samples that demonstrate the fork/join framework. The ThreadLocalRandom class eliminates contention among threads using pseudo-random numbers; see Concurrent Random Numbers. The Phaser class is a new synchronization barrier, similar to CyclicBarrier. Rich Internet Applications (RIA) and Deployment The window of a dragged applet can be decorated with a default or custom title; see Requesting and Customizing Applet Decoration in Draggable Applets. The following enhancements have been made to the syntax of JNLP files; see JNLP File Syntax: The os attribute in the information and resources elements can now contain specific versions of Windows, such as Windows Vista or Windows 7. Applications can use the install attribute in the shortcut element to specify their desire to be installed. Installed applications are not removed when the Java Web Start cache is cleared, but can be explicitly removed using the Java Control Panel. Java Web Start applications can be deployed without specifying the codebase attribute; see Deploying Without Codebase A JNLP file can be embedded into an HTML page; see Embedding JNLP File in Applet Tag. You can check the status variable of the applet while it is loading to determine if the applet is ready to handle requests from JavaScript code; see Handling Initialization Status With Event Handlers. You now have control of the window decoration style and title of an applet launched from a shortcut or dragged out of the browser; see Requesting and Customizing Applet Decoration in Developing Draggable Applets. Java 2D A new XRender-based Java 2D rendering pipeline is supported for modern X11-based desktops, offering improved graphics performance; see the xrender flag in System Properties for Java 2D Technology. The JDK now enumerates and displays installed OpenType/CFF fonts through methods such as GraphicsEnvironment.getAvailableFontFamilyNames; these fonts are also recognized by the Font.createFont method. See Selecting a Font. The TextLayout class supports Tibetan script. libfontconfig, a font configuration API, is used to select fonts to use for the logical fonts for some implementations of Linux; see Fontconfig. Java XML This release contains Java API for XML Processing (JAXP) 1.4.5, supports Java Architecture for XML Binding (JAXB) 2.2.3, and supports Java API for XML Web Services (JAX-WS) 2.2.4. Internationalization Unicode 6.0.0 is supported; see Unicode in The Java Tutorials. The directory <Java home>/demo/jfc/Font2DTest/ contains samples that demonstrate Java support for Unicode 6.0. Java SE 7 can accommodate new currencies that are identified by their ISO 4217 codes; see the Currency class. java.lang Package Potential deadlocks were eliminated for multithreaded, non-hierarchically delegating custom class loaders; see Multithreaded Custom Class Loaders in Java SE 7. Java Programming Language The following enhancements have been added to the Java language: Binary Literals Underscores in Numeric Literals Strings in switch Statements Type Inference for Generic Instance Creation Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods The try-with-resources Statement Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking Java Virtual Machine Java Virtual Machine Support for Non-Java Languages: Java SE 7 introduces a new JVM instruction that simplifies the implementation of dynamically typed programming languages on the JVM. Garbage-First Collector is a server-style garbage collector that replaces the Concurrent Mark-Sweep Collector (CMS). Java HotSpot Virtual Machine Performance Enhancements JDBC 4.1 JDBC 4.1 introduces the following features: The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement; see Closing Connections in Processing SQL Statements. RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class, which enable you to create all types of row sets supported by your JDBC driver; see Using the RowSetFactory Interface in Using JdbcRowSet Objects.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cocosum

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值