简体   繁体   中英

fileinputstream to read a given file in a particular order and store in byte[] array

I want to develop a program in java wherein the program reads a file using FileInputStream and then separates all the commas(,) and stores the rest of the values in a byte[] array. for eg. if my file "a.txt" contains 1,2,3,-21,-44,56,35,11 i want the program to read this file and store the data in a byte array which will contain

byte[] b{1,2,3,-21,-44,56,35,11}.

i have tried to read the file using FileInputStream.read() but after comparing the character for a comma it points to the next character. can anyone help me out with the code.

import java.io.*;
class a
{

public static void main(String args[])
{
    FileInputStream fis;
    int inputSize;
    try {
    fis = new FileInputStream("New.txt");
    inputSize = fis.available();
    for(int i=0;i<inputSize;i++)
    {
        if(fis.read()!=44)
        System.out.print((char)fis.read()); 
    }
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}
}

this might help you out:

private static final String DELIM = ",";
public static void main(String args[]) throws Exception {
    // ...
    // read the file content line by line with BufferedReader

    String line = "5,37,2,-7";
    String splitted[] = line.split(DELIM);
    byte[] result = new byte[splitted.length];

    for (int n = 0; n < splitted.length; ++n) {
        result[n] = Byte.parseByte(splitted[n]);
    }

    System.out.println(Arrays.toString(result));
}

Here's how you can process your file line-by-line:

    FileInputStream fis = ...;

    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String line = null;
    while ((line = br.readLine()) != null) {
        // process the String line
    }
if(fis.read()!=44)
    System.out.print((char)fis.read());

You call read() twice, so 2 characters will be read and your code prints only the second character. That's why you are wondering about

but after comparing the character for a comma it points to the next character

That gives the clou:

int readChar;
if((readChar = fis.read()) != 44)
    System.out.print((char)readChar);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM