【问题标题】:Removing column names while reading content through Inputstream in Java通过 Java 中的 Inputstream 读取内容时删除列名
【发布时间】:2014-11-07 05:40:09
【问题描述】:

我一直在尝试删除在阅读http get 返回的响应内容时出现的列名。

最初我使用http get 获取内容,然后使用InputStream 读取此内容,然后使用FileOutputStreamcsv 文件写入本地磁盘:

InputStream read_content = result.getEntity().getContent();
FileOutputStream writ = new FileOutputStream(new File(path));
byte[] buff = new byte[4096];
int length;
while ((length = read_content.read(buff)) > 0) {
     writ.write(buff, 0, length);
 }

这里的result 是我从http get 得到的回复。这很好用,但问题是 响应还包含我要删除的列名

经过一些修改,我现在正在使用此代码,但输出不正确:

           InputStream read_content = result.getEntity().getContent();

            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(read_content));

            FileWriter fstream = new FileWriter(path);
            BufferedWriter out = new BufferedWriter(fstream);
            reader.readLine();
            while (reader.readLine() != null) {
                out.write(reader.read());
            }

当我执行此修改后的代码时,我得到垃圾结果。我在这里做错了什么,如何删除表列名?

【问题讨论】:

  • 包含什么标题?
  • @EJP 很抱歉不清楚。标题包含表列名称
  • @EJP 你能告诉我如何使用BufferedReader.readLine() 删除列名吗?
  • 我认为您以正确的方式进行操作,但是您正在使用reader.read() 写入文件,即使您在写入之前调用了reader.readLine(),这也会从第一行读取。可能会使用另一种替代方法写入文件
  • @looser 很抱歉,但我无法清楚地理解您的意思。一些建议是在写入 csv 之前使用reader.readline(),所以我使用了它,但它弄乱了整个输出.你能指出我哪里出错了,我怎样才能纠正我上面的代码才能正常工作。

标签: java inputstream bufferedreader fileoutputstream bufferedwriter


【解决方案1】:

你的代码应该是这样的

           BufferedReader br = null       ;
                   BufferedWriter out = null;
    try{

        InputStream is = new FileInputStream(new File("C:/Space/ConnTest/Test/input.txt"));
         br = new BufferedReader(new InputStreamReader(is));
         out = new BufferedWriter(new FileWriter(new File("C:/Space/ConnTest/Test/output.txt")));
        System.out.println("This is first line ---"+br.readLine());
        String str = "";
        while ((str = br.readLine()) != null) {
            out.write(str);
        }
        System.out.println("Success");




    }
    catch(Exception e )
    {
        e.printStackTrace();
    }
    finally
    {
        if(br!=null)
        {
            br.close();
        }
        if(out!=null)
        {
            out.close();
        }
    }

不要与整个代码混淆,我只是用

替换了您的 out.write(reader.read());
  while ((str = br.readLine()) != null) {
            out.write(str);
        }

我在SYSOUT 中调用br.readLine(),因此标题将被跳过。然后我用br.readLine()写文件

【讨论】:

  • 我试过这种方式。即使第一行被删除,但之后的所有内容都作为一行而不是多行写入文件。当时我使用以前的方式时分别获取所有行
  • 我在里面使用了out.newline(),现在输出看起来正确。
【解决方案2】:

如果是一行,其余内容也是如此,请使用BufferedReader.readLine(), 并跳过第一行。

【讨论】:

  • 你能告诉我如何使用 BufferedReader.readLine() 读取http get 响应并在写入csv 文件时删除列名吗?
  • 呃,在开始复制到 CSV 之前,请致电 readLine() 一次?
  • 我修改了我的代码,但现在输出不正确。我已经修改了上面的帖子以包含我更新的代码。你能告诉我我做错了什么吗?
猜你喜欢
  • 2010-12-18
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多