io流操作 读取文件 返回json等

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sinosoft.splatform.persistent.model.gwlzxt.*;
import com.sinosoft.splatform.service.gwlzxt.*;

import com.sinosoft.splatform.util.PostMenHu;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

 

 

 //  从本地读取文件,然后返回文件流   这么做的目的是模仿调用 返回流的接口,  可以调用本地文件来实现  调用第二个方法就行   ----------------------

  @ResponseBody
    @RequestMapping("/getUrlFile")
    public void getUrlFile(String url, HttpServletRequest request, HttpServletResponse response) {
    
        String serverUrl = "C:/\\Users/\\15733/\\Desktop/\\28045111.pdf";
        File file = new File(serverUrl);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            response.setContentType("text/plain; charset=utf-8"); 
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//  返回的类型可以按照自己的功能封装

  public MultipartFile getIo(String title) {
        MultipartFile multipartFile;
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try{
            URL url = new URL("http://localhost:8085/ProPushDocumentController/getUrlFile");
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset="+"utf-8");
            urlConnection.connect();
            inputStream = urlConnection.getInputStream();
            multipartFile = new MockMultipartFile(title,title,"", inputStream);
            return multipartFile;
        }catch (Exception e){
            System.out.println("getFile error: " + e);
        }finally {
            try {
                inputStream.close();
                  urlConnection.disconnect();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

----------------------------结束 -------------------

----------------------------开始 --------------------

  // 从本地读取文件,返回json格式   这么做的目的是模仿调用 返回json的接口,  可以调用本地文件来实现 

  @ResponseBody
    @RequestMapping("/getJsonApi")
    public com.alibaba.fastjson.JSONObject getJsonApi() throws Exception {
        String jsonStr = "";
        try {
            File jsonFile = new File("C:/\\Users/\\15733/\\Desktop/\\111.txt");
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            com.alibaba.fastjson.JSONObject jobj = JSON.parseObject(jsonStr);
            return jobj;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

 public   com.alibaba.fastjson.JSONObject apiStream() {
        CloseableHttpClient hc=HttpClients.createDefault();
        //一个get请求对象,包装的请求地址,相当于浏览器中输入了网址
        HttpPost get=new HttpPost("http://localhost:8085/ProPushDocumentController/getJsonApi");
        //当客户端关闭请求的时候,通知服务端也关闭连接。
        get.setHeader("Connection","close");
        HttpResponse resp=null;
        HttpEntity entity=null;
        try {
            resp=hc.execute(get);    
            entity=resp.getEntity();    
            String result=EntityUtils.toString(entity);
            com.alibaba.fastjson.JSONObject jo=new com.alibaba.fastjson.JSONObject();
            return jo.parseObject(result);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {  //关闭连接
                if(entity!=null)EntityUtils.consume(entity);
                if(get!=null)get.abort();
                if(hc!=null)hc.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }    
        return null;
    }

---------------------------------------结束----------------------------------------------

 

 

 

 

 

public static String loadAFileToStringDE1(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new BufferedInputStream( new FileInputStream(f) ); long contentLength = f.length(); ByteArrayOutputStream outstream = new ByteArrayOutputStream( contentLength > 0 ? (int) contentLength : 1024); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { outstream.write(buffer, 0, len); } outstream.close(); ret = outstream.toString(); //byte[] ba = outstream.toByteArray(); //ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法1用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE2(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new FileInputStream(f) ; long contentLength = f.length(); byte[] ba = new byte[(int)contentLength]; is.read(ba); ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法2用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE3(File f) throws IOException { long beginTime = System.currentTimeMillis(); BufferedReader br = null; String ret = null; try { br = new BufferedReader(new FileReader(f)); String line = null; StringBuffer sb = new StringBuffer((int)f.length()); while( (line = br.readLine() ) != null ) { sb.append(line).append(LINE_BREAK); } ret = sb.toString(); } finally { if(br!=null) {try{br.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法3用时"+ (endTime-beginTime) + "ms"); return ret; } 3个方法去读取一个大于50M的文件,当不设置jvm参数时都OutofMemery,当设置-Xmx128M时。只有方法3 可以通过,设置到-Xmx256M时也只有方法3可以通过,干脆设置512M,都可以了,运行时间如果正常的话一般都在4~5S
在Java中,可以使用各种方式读取txt文件并将其内容转换为JSON数据。以下是一种常见的方法: 1. 首先,你需要导入相关的库,包括JSON库和文件读取库。可以使用JSON库如Gson或Jackson来处理JSON数据,使用Java的IO库来读取文件。 2. 创建一个用于读取文件的File对象,并传入txt文件的路径作为参数。 3. 使用BufferedReader类来读取文件内容。可以使用readLine()方法逐行读取文件内容,并将每行的数据存储在一个字符串变量中。 4. 将读取到的字符串数据转换为JSON格式。可以使用JSON库提供的方法将字符串转换为JSON对象或JSON数组。 5. 最后,将JSON对象或数组作为结果返回。 下面是一个示例代码: ```java import java.io.BufferedReader; import java.io.FileReader; import com.google.gson.Gson; public class TxtToJsonConverter { public static void main(String[] args) { String filePath = "path/to/your/txt/file.txt"; String jsonData = convertTxtToJson(filePath); System.out.println(jsonData); } public static String convertTxtToJson(String filePath) { StringBuilder sb = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(filePath)); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); } catch (Exception e) { e.printStackTrace(); } // 使用Gson库将字符串转换为JSON格式 Gson gson = new Gson(); return gson.toJson(sb.toString()); } } ``` 请注意,上述代码仅提供了一个基本的示例,实际应用中可能需要根据具体的需求进行适当的修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大鑫不列迭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值