• webmagic之爬取数据存储为TXT


    1.获取标题建立文件TXT
    • 创建以标题命名的TXT

    public static void create(String title) throws IOException {
        Configuration config = new Configuration();
        config.set("fs.default.name", "hdfs://192.168.146.110:9000");
        DistributedFileSystem fs = (DistributedFileSystem) DistributedFileSystem.get(config);
        String pathString = "/report/Zbgg/"+title+".txt";
        FSDataOutputStream output = fs.create(new Path(pathString));
        output.close();
    }
    • 写入网址和内容

    public static void write(String txt , String str)  {
            Configuration config = new Configuration();
            config.set("fs.default.name", "hdfs://192.168.146.110:9000");
            config.set("dfs.support.append", "true");
            config.set("dfs.client.block.write.replace-datanode-on-failure.policy", "NEVER");
            config.set("dfs.client.block.write.replace-datanode-on-failure.enable", "true");
    
            try {
                DistributedFileSystem fs = (DistributedFileSystem) DistributedFileSystem.get(config);
                //文件必须存在
                String pathString = "/report/Zbgg/"+txt+".txt";
                FSDataOutputStream outpustream = fs.append(new Path(pathString));
    
                //System.getProperty("line.separator")换行
    
                outpustream.writeBytes(str);
                outpustream.writeBytes(System.getProperty("line.separator"));
                outpustream.close();
                fs.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
     

    写入TXT的内容为乱码

    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    urlConn.connect();
    DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
    String content = "传递中文的问题";
    out.writeBytes(content);
    out.flush();
    out.close();
    urlConn.disconnect();
    依照上面的方式传递中文,服务器得到的一定是一堆乱码,原因:out.writeBytes(content);该语句在转中文时候,已经变成乱码
    public final void writeBytes(String s) throws IOException {
    int len = s.length();
    for (int i = 0 ; i < len ; i++) {
    out.write((byte)s.charAt(i));
    }
    incCount(len);
    因为java里的char类型是16位的,一个char可以存储一个中文字符,在将其转换为 byte后高8位会丢失,这样就无法将中文字符完整的输出到输出流中。所以在可能有中文字符输出的地方最好先将其转换为字节数组,然后再通过write写入流,目前尝试过这种方法:把上面链接代码中的out.writeBytes(content);替换为out.write(content.getBytes());先把数据转成BYTE在写入流,执行成功,服务器接收正确的中文内容

  • 相关阅读:
    螺旋折线——第九届蓝桥杯C语言B组(省赛)第七题
    组合问题
    八皇后
    01背包(详解)
    最长递增子序列
    棋盘游戏
    The Accomodation of Students
    P3157 [CQOI2011]动态逆序对
    Building a Space Station
    焚风现象(差分模板题)
  • 原文地址:https://www.cnblogs.com/wf1647790534/p/9802985.html
Copyright © 2020-2023  润新知