Archivo txt de exportación de Java para guardar local y el navegador descarga directamente de dos maneras

La primera forma: guardar en local

paquete com.cnki.tool.base; 
 
import javax.servlet.http.HttpServletResponse;
 import java.io. * ;
 import java.util.ArrayList;
 import java.util.List; 
 
public  class ExportTxtUtil { 
    
    / ** 
     * Export 
     * 
     * archivo @param 
     * El archivo Txt (ruta + nombre del archivo), el archivo Txt no existe se creará automáticamente 
     * @param dataList 
     * data 
     * @return 
     * / 
    public  static  boolean exportTxt (archivo de archivo, List <String> dataList) { 
        FileOutputStream out= nulo ;
        pruebe { 
            out = new FileOutputStream (archivo);
            return exportTxtByOS (fuera, dataList); 
        } catch (FileNotFoundException e) { 
            e.printStackTrace (); 
            devuelve  falso ; 
        } 
    } 
 
    / ** 
     * 导出
     * 
     * @param out 
     * 输出 流
     * @param dataList 
     * 数据
     * @return 
     * / 
    public  static  booleanexportTxtByOS (OutputStream out, List <String> dataList) {
         boolean isSucess = false ; 
        OutputStreamWriter osw = null ; 
        BufferedWriter bw = null ;
        pruebe { 
            osw = new OutputStreamWriter (out); 
            bw = nuevo BufferedWriter (osw);
            // 循环 数据
            for ( int i = 0; i <dataList.size (); i ++ ) { 
                bw.append (dataList.get (i)). Append ( "\ r \ n" ); 
            }
            
            isSucess = true ; 
        } catch (Excepción e) { 
            e.printStackTrace (); 
            isSucess = false ; 
 
        } finalmente {
             if (bw! = null ) {
                 try { 
                    bw.close (); 
                    bw = nulo ; 
                } catch (IOException e) { 
                    e.printStackTrace (); 
                } 
            } 
            if (osw! = null) {
                 try { 
                    osw.close (); 
                    osw = nulo ; 
                } catch (IOException e) { 
                    e.printStackTrace (); 
                } 
            } 
            if (out! = null ) {
                 try { 
                    out.close (); 
                    fuera = nulo ; 
                } catch (IOException e) { 
                    e.printStackTrace (); 
                } 
            } 
        }
 
        return isSucess; 
    } 
 
    public  static  void main (String [] args) { 
        List <String> list = new ArrayList <String> (); 
        list.add ( "¡Hola, mundo!" ); 
        list.add ( "¡Hola, mundo!" ); 
        list.add ( "¡Hola, mundo!" ); 
        list.add ( "¡Hola, mundo!" ); 
 
        String filePath = "D: / txt /" ; 
        String fileName = java.util.UUID.randomUUID (). ToString (). ReplaceAll ("-", "") + ". Txt" ;Archivo (filePath);
        if (! pathFile.exists ()) { 
            pathFile.mkdir (); 
        } 
        Cadena relFilePath = filePath + File.separator + fileName; 
        Archivo de archivo = archivo nuevo (relFilePath);
        if (! file.exists ()) { 
            file.createNewFile (); 
        } 
        boolean isSuccess = exportTxt (archivo, lista); 
        System.out.println (isSuccess); 
        } 
 
}

 


La segunda forma de descargar el navegador directamente:

    / * 拼接 字符串
     * @author     
     * @param 
     * @return 
     * / 
    @RequestMapping ( "exportLog.do" )
     public  void exportLog (respuesta HttpServletResponse) {
         // 获取 日志 
        List <DtmSystemLog> list = logService.getLogs ();
        // 拼接 字符串 
        StringBuffer text = new StringBuffer ();
        for (DtmSystemLog log: list) { 
            text.append (log.getOpeuser ()); 
            text.append ( "|" ); 
            text.append (log.getOpedesc ()); 
            text.append ( "|"); 
            text.append (dateString); 
            text.append ( "\ r \ n"); // carácter de avance de línea 
        } 
        exportTxt (response, text.toString ()); 
        
    } 
 
 
    / * exportar archivo txt 
     * @author     
     * @param response 
     * @param cadena de texto exportada 
     * @return 
     * / 
    public  void exportTxt (respuesta HttpServletResponse, texto de cadena) { 
        response.setCharacterEncoding ( "utf-8" );
         // Establezca el tipo de contenido de 
        respuesta response.setContentType ("text / plain " );
         // Establecer el nombre y el formato del archivo
        response.addHeader ("Content-Disposition", "adjunto; filename =" 
                            + genAttachmentFileName ("Nombre de archivo", "JSON_FOR_UCC_") // Establezca el formato del nombre, no se puede mostrar sin este nombre chino 
                        + ".txt" ); 
        BufferedOutputStream buff = null ; 
        ServletOutputStream outStr = null ;
         try { 
            outStr = response.getOutputStream (); 
            buff = new BufferedOutputStream (outStr); 
            buff.write (text.getBytes ( "UTF-8" )); 
            buff.flush (); 
            buff.close ();
        } captura(Excepción e) {
             // LOGGER.error ("Error al exportar el archivo: {}", e); 
        } finalmente { try { 
                buff.close (); 
                outStr.close (); 
            } catch (Excepción e) {
                 // LOGGER.error ("Error al cerrar el objeto de secuencia e: {}", e); 
            } 
        } 
    } 
 
// Evitar el error de visualización del nombre de archivo en chino     
 
public   String genAttachmentFileName (String cnName, String defaultName) {
         try { 
            cnName = new String (cnName.getBytes ("gb2312"), "ISO8859-1" );
        } catch(Excepción e) { 
            cnName = defaultName; 
        } 
        return cnName; 
    }

 

Método de llamada remota al navegador para descargar el archivo txt:

import org.apache.commons.io.IOUtils; 
 
    @RequestMapping ({ "/demp/common/downloadDeviceLog.do" }) 
    @ResponseBody 
    public  void downloadDeviceLog (solicitud HttpServletRequest, respuesta HttpServletResponse) lanza Exception { 
        String logUrl = "https: //**/2018-11-20.txt" ;
        pruebe { 
            String [] logUrlArray = logUrl.split ("/" ); 
            String fileName = logUrlArray [logUrlArray.length-1 ]; 
            URL url = nueva URL (logUrl); 
            URLConnection uc =url.openConnection (); 
            response.setContentType ( "aplicación / flujo de octetos"); // 设置 文件 类型 
            response.setHeader ("disposición de contenido", "archivo adjunto; nombre de archivo =" + URLEncoder.encode (nombreDeArchivo, "UTF-8" )); 
            response.setHeader ( "Content-Length" , String.valueOf (uc.getContentLength ())); 
            ServletOutputStream out = response.getOutputStream (); 
            IOUtils.copy (uc.getInputStream (), fuera); 
        } catch (Excepción e) { 
            e.printStackTrace (); 
        } 
    }

 



Supongo que te gusta

Origin www.cnblogs.com/liuminchao/p/12695965.html
Recomendado
Clasificación