2014-08-28 79 views
-1

我的目标是从文件中使用BufferedReader从字节中获取字符串,但我可以获取字符串,但有些时候结果是'带字节的字符串',因此文件被损坏。 我用readline得到第一行,但它工作,但有一段时间字符串来的字节。 下面是代码我试图做到这一点从字节获取第一行字符与出字节

public static void main(String[] args) throws IOException { 


InputStream inStream = null; 
    OutputStream outStream = null; 
    String line; 
    BufferedReader reader; 


    File afile = new File(
      "snake2.jpg"); 

    File bfile = new File(
      "snake.jpg"); 
    File file=new File("E://snake.txt"); 

    // for stream reading and writing..... 
    inStream = new FileInputStream(afile); 


    outStream = new FileOutputStream(bfile); 
    OutputStream txt=new FileOutputStream(file); 
    // create byte array..... 
    ByteArrayOutputStream f = new ByteArrayOutputStream(); 

    reader = new BufferedReader(new InputStreamReader(inStream)); 
    line = reader.readLine(); 
+0

去低级别'read'和测试逐字节查看是否有字符。 – 2014-08-28 07:07:50

+0

@ScaryWombat你能告诉我一个例子吗? – 2014-08-28 07:08:45

+0

可能是您的文件包含字符 – SparkOn 2014-08-28 07:11:16

回答

0

我觉得你implemetation适合于文本,而不是二进制文件:readLine似乎不适合一个jpg文件,使用read代替。 以此为例related question

+0

我想从该字节取文本文件 – 2014-08-28 07:15:49

+0

我不确定要理解,但您可以通过Arrays.toString(data.toByteArray())将'data'字节转换为字符串' – Coconop 2014-08-28 07:18:29

+0

我是在字节内写入文本'第一行'和其他结束代码它取出第一行并使真实文件如此多次文本带有一些字节,因此文件被损坏 – 2014-08-28 07:18:55

1

使用的FileInputStream读你可以在时间和测试一个字节,如果它是一个char或不

inStream = new FileInputStream(afile); 

int ch; 
while ((ch = inStream.read()) != -1) 
{ 
    if (ch >= 32 && ch <= 126) out.write (ch); // see ascii table 

}