私は入力ファイルから文字を読み込むためにJavaでBufferedReaderを使用しています。ただし、出力は珍しいです。以下の私のコードでは、私が最初に私は、個々の文字印刷するBufferedReaderのを使用して、ファイル自体の内容を表示するためにスキャナを使用します。以下はファイルから入力ストリームを読み取っていない文字を出力します
import java.util.Scanner;
import java.io.*;
//import java.io.File;
public class Inputs
{
public static void main(String[] args)
{
System.out.println("Inputs");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
System.out.println(input);
// Open the file
File file = new File("Simple.java");
try {
Scanner fileIn = new Scanner(file);
while(fileIn.hasNext()){
System.out.println(fileIn.next());
}
fileIn.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Simple.java");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
String character = Character.toString ((char) br.read());
System.out.println (character);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
を私が得る出力され、表示された最初のトークンは、スキャナであるが、ハイライトされたプリテンションの後にBufferedReaders出力が表示されます。それは3つのスペースを表示し、次に閉じた中かっこ、-1(終わり)を表示します。これの意味は何ですか?
この質問はクールだと思います。 –
あなたのコードは意味をなさない。あなたは行を読み込んでいますが、ストリームの終わりを示す-1であっても、* next *文字を印刷します。ファイルを印刷する場合は、読み込んだ行を出力します。 – EJP