1

我想从文件中读取字符串。当找到某个字符串 ( ><) 时,我想开始读取整数,并将它们转换为二进制字符串。

我的程序正在读取字符串并将它们ArrayList成功保存,但它无法识别该><符号,因此二进制字符串的读取不成功。

编码


try {
    FileInputStream fstream = new FileInputStream(fc.getSelectedFile().getPath());
    // Get the object of DataInputStream
    DataInputStream ino = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(ino));
    String ln;
    String str, next;
    int line, c =0;

    while ((ln = br.readLine()) != null) {
        character = ln;
        System.out.println(character);
        iname.add(ln); // arraylist that holds the strings
        if (iname.get(c).equals("><")) {
            break; // break and moves
            // on with the following while loop to start reading binary strings instead.

        }
        c++;
    }

    String s = "";
    // System.out.println("SEQUENCE of bytes");

    while ((line = ino.read()) != -1) {
        String temp = Integer.toString(line, 2);
        arrayl.add(temp);
        System.out.println("telise? oxii");
        System.out.println(line);
    }

    ino.close();

} catch (Exception exc) { }

我试图阅读的文件是例如:

 T 
 E 
 a
 v 
 X 
 L 
 A 
 . 
 x 
 "><" 
 sequence of bytes.

最后一部分保存为字节并且在文本文件中看起来像这样。不用担心这个位有效。所有字符串都保存在新行中。

4

3 回答 3

0

你能不能做这样的事情:

while ((ln = br.readLine()) != null){
            character=ln;
            System.out.println(character);

            //
            // Look for magic characters >< and stop reading if found
            //

            if (character.indexOf("><") >= 0) {
               break;
            }

            iname.add(ln);
    }

如果您不想将魔术符号添加到 ArrayList,这将起作用。您的代码示例不完整 - 如果您仍然遇到问题,您需要发布整个课程。

于 2011-03-18T15:30:28.417 回答
0

< 是两个字符,而 iname.get(c) 只是一个字符。

您应该做的是测试 ln 是否等于 > ,然后再测试下一个字符是否等于 < 。如果两个测试都通过,则跳出循环。

你必须小心

于 2011-03-18T15:30:55.747 回答
0

使用扫描仪。它允许您指定分隔符,并具有将输入标记读取为 String 或 int 的方法。

于 2011-03-18T15:47:47.480 回答