0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】read()メソッドで取得するテキストファイルの文字の整数情報

Posted at

参考図書

Javaの絵本 第3版 Javaが好きになる新しい9つの扉
https://www.amazon.co.jp/Java%E3%81%AE%E7%B5%B5%E6%9C%AC-%E7%AC%AC3%E7%89%88-Java%E3%81%8C%E5%A5%BD%E3%81%8D%E3%81%AB%E3%81%AA%E3%82%8B%E6%96%B0%E3%81%97%E3%81%849%E3%81%A4%E3%81%AE%E6%89%89-%E6%A0%AA%E5%BC%8F%E4%BC%9A%E7%A4%BE%E3%82%A2%E3%83%B3%E3%82%AF/dp/4798150371

※サンプルプログラムに手を加えて引用しています。

文字情報を読み込むサンプルプログラム

ReadText.java
import java.io.FileReader;
import java.io.IOException;

public class ReadText {

	public static void main(String[] args) {
		try {
			FileReader in = new FileReader(args[0]);
			int c;
			String s = new String();
			System.out.println("****文字整数のそのまま表示****");
			while((c = in.read()) != -1) {
				System.out.print(c); // 文字の整数情報を出力
				System.out.println();
				s = s + (char)c; // 整数情報を文字に変換
			}
			System.out.print(s); // 文字に変換して結合した文字列を出力
			in.close();
		} catch (IOException ie) { // 入出力時の例外を表す例外クラス
			System.out.println("ファイルがありません");
		} catch (Exception e) {
			System.out.println("ファイル指定がありません");
		}
	}
}

aiueo.txt
あいうえお
かきくけこ
さしすせそ

最後の「そ」の後にも改行を入れています

実行結果

実行結果
****文字整数のそのまま表示****
12354
12356
12358
12360
12362
10
12363
12365
12367
12369
12371
10
12373
12375
12377
12379
12381
10
あいうえお
かきくけこ
さしすせそ

ひらがな一つは5つ、改行は10で表す

10が3回出てきてます。aiueo.txtのそれぞれの行の最後に改行を入れているので改行は10のようですね。

PHPより入出力がめんどくさい

多分PHPだけじゃなくてRubyももっと簡単に記述ができるのでしょう。

しかしテキストファイルとのデータのやりとりの方法などは、いちいち記述しないといけないが故に、中身も見えて理解が深まる気がします。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?