-2

I have an BufferedinputStream that contains the byte[] representation of a file file and before that it contains the name of file ("FileName.fileExtension") I'd like to read the first line and then read the byte representation of the file so I can Convert It to the it's extension I tried this but it didn't work and because i have to keep the byte[] representation of the file

BufferedInputStream bis=new BufferedInputStream(sr.getInputStream());
    BufferedReader in=new BufferedReader(new InputStreamReader(sr.getInputStream()));
    String Filename=in.readLine();
    String y=in.lines().collect(Collectors.joining());
ABK
  • 9
  • 1
  • 8
  • Hint: `in.readLine()` is wrong. Try to find another solution for reading the file, stream, resource... – zlakad Mar 13 '18 at 20:15
  • @zlakad I actually use IOUtils from Apache byte[] x = IOUtils.toByteArray(bis); But I cannot get the first line when using it – ABK Mar 13 '18 at 20:18
  • I don't use `Apache byte`, but I suggest that you read the first line, than get rid of it, and than use `Apache byte` for the rest of file – zlakad Mar 13 '18 at 20:24

2 Answers2

0

You don't have to always use streams but you need to close the resources. Maybe what you want can be achieved with standard Scanner and ByteArrayOutputStream:

String fileName = null;
byte[] content = null;

try (InputStream in = sr.getInputStream()) {
  Scanner s = new Scanner(in); // might have to call useDelimiter()
  fileName = s.nextLine(); // skips line delimiter from the stream

  ByteArrayOutputStream buf = new ByteArrayOutputStream();
  int read;
  byte[] data = new byte[1024];
  while ((read = in.read(data, 0, data.length)) != -1) {
    buf.write(data, 0, read);
  }
  content = buf.toByteArray();
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

You can do it the following way:

List<String> data = new ArrayList<>();
//Read all the lines first.
List<String> lines = Files.lines(Paths.get(Filename)).collect(Collectors.toList());
//Store the first line in a header
String header = lines.stream().findFirst().get();
//Store the remaining lines in a list of lines.
lines.stream().skip(1).forEach(s -> data.add(s));
VHS
  • 9,534
  • 3
  • 19
  • 43
  • OP wants to read first line as the line, **and the rest** of file like byte[] – zlakad Mar 13 '18 at 20:20
  • I guess I haven't made my self clear I Recieve an Input stream containing the file name in this example ABK.png and then the byte[] representation of the file i'd like to Extract the name and then the rest of the input keeping it in it's byte format (not String so I won't have any problems in Converting to the file original format). ABK.png‰PNG IHDR   È–˜ sBITÛáOà IDATxœìy@×úþg²°Â¾Cd0àŠ¨ ˆR‘ îz]âÞk[…Zj´×ªmE´­ÖÔ.Ö]+"¢€UQ«² . „5l – ABK Mar 13 '18 at 20:28
  • So if you are already getting the filename and byte array separately, how do they get mixed up? – VHS Mar 13 '18 at 20:33