-1

My goal is to get string from a file with out bytes using BufferedReader but i can get the string but some times the result is 'string with bytes' so the files getting corrupted. I used readline to get the 1st line but it working but some time the bytes coming with the string. Here is the code am trying to do it

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();

3 Answers3

1

using the FileInputStream read you can get one byte at a time and test if it is a char or not

inStream = new FileInputStream(afile);

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

}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

I think your implemetation fits for text, not binary files: readLine seems not appropriate for a jpg file, use read instead. Cf this related question for an example.

Community
  • 1
  • 1
n0p
  • 3,399
  • 2
  • 29
  • 50
  • I want to take text file from that bytes – George Jeffin Aug 28 '14 at 07:15
  • I am not sure to understand but you can convert `data` bytes to string with `Arrays.toString(data.toByteArray())` – n0p Aug 28 '14 at 07:18
  • I am writing text inside bytes the '1st line' and other end code it takes out 1st line and make the real file so some times the text comes with some bytes so the file getting corrupted – George Jeffin Aug 28 '14 at 07:18
  • In your example you just read a `.jpg` as it was a `.txt`. Could you clarify what you are trying to accomplish ? Does `snake.jpg` contains characters ? What is important in the 1st line ? And BTW text (characters) are ultimately bytes... – n0p Aug 28 '14 at 07:27
  • snake.jpg contains characters Yup the 1st line.Another code i made it take the text from the snake.jpp but the problem is the text comes with some bytes so the file getting corrected – George Jeffin Aug 28 '14 at 07:32
  • I don't think `jpg` files have "lines". Anyway, you should use `read` instead of `readline`. As proposed above, test if the read byte is a character and if so, don't recopy it into the output file. – n0p Aug 28 '14 at 07:39
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/60148/discussion-between-george-jeffin-and-coconop). – George Jeffin Aug 28 '14 at 07:45
0

Make a look at java.nio.channels.FileChannel

guleryuz
  • 2,714
  • 1
  • 15
  • 19