简体   繁体   English

fileinputstream以特定顺序读取给定文件并存储在byte []数组中

[英]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. 我想用Java开发一个程序,其中该程序使用FileInputStream读取文件,然后分离所有逗号(,),并将其余值存储在byte []数组中。 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 如果我的文件"a.txt"包含1,2,3,-21,-44,56,35,11我希望程序读取此文件并将数据存储在字节数组中,该字节数组将包含

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. 我尝试使用FileInputStream.read()读取文件,但是在比较了逗号字符后,它指向下一个字符。 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. 您两次调用read() ,因此将读取2个字符,并且您的代码仅输出第二个字符。 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: 这给出了clou:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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