zoukankan      html  css  js  c++  java
  • String/InputStream/File之间的相互转换

    InputStream与String之间转换

    String转InputStream

    /**
     * 将str转换为inputStream
     * @param str
     * @return
     */
    public static InputStream str2InputStream(String str) {
    	ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());
    	return is;
    }
    

    InputStream转String

    /**
     * 将inputStream转换为str
     * @param is
     * @return
     * @throws IOException
     */
    public static String inputStream2Str(InputStream is) throws IOException {
    	StringBuffer sb;
    	BufferedReader br = null;
    	try {
    		br = new BufferedReader(new InputStreamReader(is));
    
    		sb = new StringBuffer();
    
    		String data;
    		while ((data = br.readLine()) != null) {
    			sb.append(data);
    		}
    	} finally {
    		br.close();
    	}
    
    	return sb.toString();
    }
    

    InputStream与File之间转换

    File转InputStream

    /**
     * 将file转换为inputStream
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public static InputStream file2InputStream(File file) throws FileNotFoundException {
    	return new FileInputStream(file);
    }
    

    InputStream转File

    /**
     * 将inputStream转化为file
     * @param is
     * @param file 要输出的文件目录
     */
    public static void inputStream2File(InputStream is, File file) throws IOException {
    	OutputStream os = null;
    	try {
    		os = new FileOutputStream(file);
    		int len = 0;
    		byte[] buffer = new byte[8192];
    
    		while ((len = is.read(buffer)) != -1) {
    			os.write(buffer, 0, len);
    		}
    	} finally {
    		os.close();
    		is.close();
    	}
    }
    
  • 相关阅读:
    LeetCode-Palindrome Partitioning II
    LeetCode-Palindrome Partitioning
    LeetCode-Permutation Sequence
    LeetCode-Anagrams
    LeetCode-Text Justification
    LeetCode-Best Time to Buy and Sell Stock III
    LeetCode-Best Time to Buy and Sell Stock II
    LeetCode-Best Time to Buy and Sell Stock
    LeetCode-N-Queens II
    BZOJ 5390: [Lydsy1806月赛]糖果商店
  • 原文地址:https://www.cnblogs.com/dulinan/p/12033007.html
Copyright © 2011-2022 走看看