检查文本文件中的每个字符,Java

时间:2016-05-03 16:54:44

标签: java bufferedreader file-handling

我有一个文本文件,当我读取文件的每一行并将其写入数组时。我想检查这个角色是不是美元符号'$'。如果是,则跳转到下一个字符并写下面的部分直到下一个数组中的下一个美元符号。因此要将每一行划分为3个部分,每个部分都在不同的数组中。

感谢您的时间和帮助!

public void retrieveFromTxt()抛出IOException

{
    textArea.setText(" ");
    String fileName = "Name_Of_City.txt";
    String line = " ";
    String entry = null;
    y = 0;

    char letter = '$', value = ' ';
    FileReader fileReader = new FileReader(fileName);
    BufferedReader br1 = new BufferedReader(fileReader);
    String TextLine = br.readLine();

    x = 1; // Random Variable to jump from character to character in array.
    // To Get Values Back from FIle Each value in correct array, I seperated each value with "$" sign 
    // Checking each letter and printing it to array[y] possition until the $ sign is met, then jump over it and continue in other array.
    try { 

        while(y < 19) {
            while(TextLine != null) {
                while(TextLine.charAt(x)!=(letter)) {
                    line = line +  TextLine.charAt(x);
                    Country[y] = ( line  );
                    x++;
                }
            }
            while(TextLine != null) {
                while(TextLine.charAt(x)!=(letter)) {
                    line = line +  TextLine.charAt(x);
                    City[y] = ( line  );
                    x++;
                }
            }
            while((line = br1.readLine()) != null) {
                while(line.charAt(x)!=(letter)) {
                    Population[y] = (textArea.getText()+ entry );

                    x++;
                }
            }
            y++;
            textArea.setText(textArea.getText()+ "\n" );
        }

    }
    catch(FileNotFoundException error) {
        //Exception can be met if program cannot find the file , in that case messageDialog will pop up with help message
        JOptionPane.showMessageDialog(null,"Missing file"+",     " + fileName + ",     for a support contact oleninshelvijs@gmail.com!" ) ;
    }catch (StringIndexOutOfBoundsException err){}
    br1.close();
}

}

2 个答案:

答案 0 :(得分:2)

尝试使用string.split函数。你可以这样做:

String s = "my$sign"
String parts[] = s.split("\\$")

现在零件[0]将保持&#34;我的&#34;和部分[1]将举行&#34;签署&#34;。

编辑:正如下面的用户Ukfub所指出的,您需要转义符号。更新我的代码以反映。

答案 1 :(得分:0)

String parts [] = s.split(&#34; $&#34;)

这不起作用,因为&#34; split&#34;的参数method是一个正则表达式。你必须逃避特殊角色&#39; $&#39;:

String parts[] = s.split("\\$")