1

読み取り中にファイルからスペースを削除しようとしています。これを行うには、char の ASCII コードをチェックします。127 (スペース) でない場合は、それを出力します。

それを考えるより良い方法は何ですか?またはこの方法で修正する方法は?

private FileInputStream sc;
private static char input;

public void openFile(){
try{
    sc = new FileInputStream(new File ("D:\\Empty.txt"));
    input = (char) sc.read();
    if(input != 127){
        System.out.println(input);
    }
}catch(FileNotFoundException e){
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
}

public static void main(String[] args) {

    ParsingStrings ps = new ParsingStrings();
    ps.openFile();

}
4

6 に答える 6

4

char リテラルを使用して、より明確に (そして明らかに正しく) してみませんか?

if (input != ' ')

また、バイナリ データの読み取りには Streams を使用する必要があります。テキストを読むには、Reader を使用する必要があります。Java IO チュートリアルを読んでください。

そしてもちろん、メソッドはそのような例外を食べるべきではありません。それらをスローするか、少なくとも別の例外でラップして、この例外をスローする必要があります。

openFile()最後に、Reader はフィールドではなく、メソッドのローカル変数にする必要があります。そして、finally ブロックで閉じるか、Java 7 の try-with-resources コンストラクトを使用して閉じる必要があります。

于 2013-03-23T15:38:32.327 に答える
3

BufferedReader でラップされた FileReader などの文字ストリームは、文字単位で読み取るため、使用できます。バイトの読み取りと、あなたが行っている方法でのキャラクターとしてのキャストに問題があると思います。

    String s;
    BufferedReader in = new BufferedReader(new FileReader("file.txt"));
    while ((s = in.readLine()) != null) {
        for (char c : s.toCharArray()) {
            if (c != ' ') {
                System.out.println(c);
            }
        }
    }
于 2013-03-23T15:39:53.247 に答える
1

ASCII スペースは 32、127 は DEL です。http://en.wikipedia.org/wiki/ASCIIを参照

于 2013-03-23T15:40:19.760 に答える
0

You have two options:

  1. If you want to remove spaces from input, take a look at the FilterInputStream class. Override the read() method: if it reads a space character, let it read one character further.

  2. If you want to remove spaces from output, take a look at the FilterOutputStream class. Override the write(int) method: if it is called to write a space character, let it do nothing.

In your particular case, I'd opt for the latter option, as I think it's a bit easier to implement, but the choice is yours.

于 2013-03-23T15:40:28.207 に答える
0
sc = new FileInputStream(new File ("D:\\Empty.txt"));

while(sc.hasNextLine()){
    input = sc.nextLine().replace(" ","");
    System.out.println(input);
}

ファイル全体からスペースを削除して印刷したい1文字だけをチェックする代わりに...はい?

于 2013-03-23T15:50:54.903 に答える
0

BufferedReader と InputStreamReader を使用すると役立ちます。このようにして、.readLine() を使用してファイルの各行を読み取り、.charAt() を使用してその行から各文字を読み取ることができます。

お役に立てれば

于 2013-03-23T15:43:23.910 に答える