-1

For writing a string of data into a file using fileoutputstream we go for converting for string into byte array.For reading a string of data using fileinputstream we can't use convertion. what is the reason for that?

reading:

class Test {
  public static void main(String args[]) {
    try {
      Fileinputstream fin = new Fileinputstream("abc.txt");
      int i = 0;
      while ((i = fin.read()) != -1) {
        System.out.print((char) i);
      }
      fin.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

writing:

class Test {
  public static void main(String args[]) {
    try {
      FileOutputstream fout = new FileOutputStream("abc.txt");
      String s = "Sachin Tendulkar is my favourite player";
      byte b[] = s.getBytes(); //converting string into byte array
      fout.write(b);
      fout.close();
      System.out.println("success...");
    } catch (Exception e) {
      system.out.println(e);
    }
  }
}
Vengade Sh
  • 42
  • 8
  • 1
    Unclear what you mean. Please provide an example. – Andy Turner Nov 04 '16 at 09:59
  • 1
    What do you mean? FileInputStream has a read(byte[]) method which reads from the file into a byte[]. Converting that to a string is trivial (There's a constructor in String) – Matt Fellows Nov 04 '16 at 10:00
  • 1
    @MattFellows "Converting that to a string is trivial" trivial, but easy to do incorrectly. – Andy Turner Nov 04 '16 at 10:02
  • @AndyTurner indeed, unless you are blessed to only have to work with single byte characters in your locale's encoding. – Matt Fellows Nov 04 '16 at 10:05
  • @MattFellows blessing doesn't come into it; and even "only having to work with single byte characters" doesn't work if your JVM's default encoding is set incorrectly. You simply need to know the character encoding used to write the string to the file. – Andy Turner Nov 04 '16 at 10:06
  • @AndyTurner Not sure if you think you are educating me here, but you aren't. I was merely agreeing with you. I'm fully aware of the pitfals of character encoding, as i'm sure is anyone who's ever had to convert a byte[] to a String, unless the defaults happen to apply to every byte[] they've ever converted. – Matt Fellows Nov 04 '16 at 10:09
  • @MattFellows "as i'm sure is anyone who's ever had to convert a byte[] to a String" OP's code shows he doesn't understand it. It's not always for *your* benefit, y'know. – Andy Turner Nov 04 '16 at 10:10
  • @AndyTurner No but you are replying to me - think this might have got a bit out of hand. – Matt Fellows Nov 04 '16 at 10:12
  • fileoutputstream writes only primitive values not string. then how can fileinputstream can read both string and primitive values – Vengade Sh Nov 04 '16 at 10:12
  • @VengadeSh I think you need to understand the difference between streams (which are byte-oriented) and readers/writers (which are character-oriented). Try searching for "difference between stream and reader", e.g. http://stackoverflow.com/questions/4367539/what-is-the-difference-between-reader-and-inputstream. – Andy Turner Nov 04 '16 at 10:17

2 Answers2

-1

FileInputStream only reads primitive values and FileOutputStream only writes primitive values (And arrays of those primitives).
String has a constructor for a byte[] and a method to get the byte[] of its data, there's no disparity here...

String s = new String("The Data");
byte[] bytesToWrite = s.getBytes();
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytesToWrite);

vs

FileInputStream fis = new FileInputStream(file);
byte[] bytesRead = new byte[8];
fis.read(bytesRead);
String s2 = new String(bytesRead);

EDIT: This code is not safe, is not best practice and should under no circumstances be used. It is merely demonstrating the symmetry betwen Input and Output Streams. In fact if you are dealing with streams yourself, you may want to consider using a library to deal with buffering, reading the correct number of bytes etc for you. I'd highly recommend Apache Commons IOUtils project for this kind of stuff...

Matt Fellows
  • 6,512
  • 4
  • 35
  • 57
  • the first example i have given is able to read a string of character? – Vengade Sh Nov 04 '16 at 10:17
  • i think it read a single character each time,not a full string......am i correct?? – Vengade Sh Nov 04 '16 at 10:18
  • You should really be directing the user to use readers/writers to read/write characters, not use streams. – Andy Turner Nov 04 '16 at 10:18
  • byte b[] = s.getBytes(); //converting string into byte array it is done by using streams sir – Vengade Sh Nov 04 '16 at 10:19
  • @VengadeSh there are two read methods on Streams, onwe which reads a single byte `Stream.read()` and one which reads as many bytes as you want to buffer, `Stream.read(byte[])`. The second method can be used to read as much as you want at a time, and fills the passed in byte[] with data from the Stream. As @AndyTurner is pointing out though, it sounds like you may want to look up Writers, as opposed to Streams. They are geared towards Strings and characters, rather than raw bytes. – Matt Fellows Nov 04 '16 at 10:23
  • stream is a bytes,so that we convert string to byte – Vengade Sh Nov 04 '16 at 10:23
  • @MattFellows : your second sample is dangerous : you shloud not discard the return value of `fis.read(bytesRead)`, which holds the number of values actually read and copied to the buffer. Failing to do so will result in a `s2` String having boggus null characters. Even if just illustrating the symetry of the methods (which is why I guess you also left out anything related to encodnigs), this is kind of dangerous to neglect. – GPI Nov 04 '16 at 10:34
  • @GPI and if I was writing a tutorial on how to read and write data from streams I totally would have. But the code I wrote won't even compile, and it was just to demonstrate the symmetry (Which was the question). I'll caveat the code with warnings though. – Matt Fellows Nov 04 '16 at 10:36
  • Fair enough ! Maybe it was just me, but that's such a common mistake that even in passing, it might seem legitimate to IO newbies. – GPI Nov 04 '16 at 10:44
-1

You could do it similar to this examples:

Read all bytes and convert it to a single string:

try ( FileInputStream fis = new FileInputStream("file.txt")) {
    final byte[] buffer = new byte[1024];
    int count;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((count = fis.read(buffer)) != -1) {
        bos.write(buffer, 0, count);
    }
    return new String(bos.toByteArray());
}

Read all lines as a list of strings:

try (FileInputStream fis = new FileInputStream("file.txt");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader reader = new BufferedReader(isr)) {
    List<String> lines = new ArrayList<>();
    String line;
    while ((line = reader.readLine()) != null) {
        lines.add(line);
    }
    return lines;
}

Other examples and maybe some best practises can be found here: How do I create a Java string from the contents of a file?

Community
  • 1
  • 1
ST-DDT
  • 2,615
  • 3
  • 30
  • 51
  • 1
    Your first example is a really dangerous implementation. You are reading bytes in chunks of arbitrary size, and expecting to be able to make a String out of each chunk. One way this will fail is if a multi-byte character is split between two reads, allocating a String from the buffer is bound to fail. See this question (among others) : http://stackoverflow.com/questions/28969941/inputstream-and-utf-8-sometimes-shows-characters – GPI Nov 04 '16 at 10:28
  • Agreed, this particular issue has been adressed :-) – GPI Nov 04 '16 at 10:46