java 文件上傳 與 把文件解析成一個字節數組簡單的後臺示例

工具類:

public static void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException {         
        FileOutputStream fs=new FileOutputStream( path + "/"+ filename);   
        byte[] buffer =new byte[1024*1024];   
        int bytesum = 0;   
        int byteread = 0;    
        while ((byteread=stream.read(buffer))!=-1)   
        {   
           bytesum+=byteread;   
           fs.write(buffer,0,byteread);   
           fs.flush();   
        }    
        fs.close();   
        stream.close();         
    }  
	
	public static byte[] readFile(File f_file) throws Exception{
		InputStream is = null;
	       ByteArrayOutputStream out = new ByteArrayOutputStream();
	       try {
	           is = new FileInputStream(f_file);// pathStr 文件路徑
	           byte[] b = new byte[1024];
	           int n;
	           while ((n = is.read(b)) != -1) {
	               out.write(b, 0, n);
	           }// end while
	       } catch (Exception e) {
	           throw new Exception("System error,SendTimingMms.getBytesFromFile", e);
	       } finally {
	           if (is != null) {
	               try {
	                   is.close();
	               } catch (Exception e) {
	               }// end try
	           }// end if
	       }// end try
	    
	    byte[] temp = out.toByteArray();
	    
	    return temp;
	}

調用測試:

	public static void main(String[] args) {
		
		try {
			FileInputStream fileInputStream = new FileInputStream(new File("D:/asd2019-09-09.xls"));
			SaveFileFromInputStream(fileInputStream, "E:/", "asd.txt");
			byte[] str = readFile(new File("D:/asd2019-09-09.xls"));
			System.out.println(str);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}


發佈了94 篇原創文章 · 獲贊 52 · 訪問量 64萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章