Instead of using the scanner class in java, we create a program that reads the string entered line by line until a blank character is entered and writes it to a file if a blank character is entered.
Example) If you type 12, aaa, 3b and then line feed without entering anything, 12, aaa, 3b will appear in the text file
However, it does not work because the program does not finish well and only the first characters typed in the file are displayed indefinitely.Please tell me how to fix it.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class TextOuter {
public static void main(String[]args) {
try{
BufferedReader buff = new BufferedReader (new InputStreamReader (System.in));
File file=new File("out/kadai8_01.txt");
FileWriter fw = new FileWriter(file);
String line = buf.readLine();
do{
if((line=buf.readLine())!=null){
fw.write(line);
} else {
break;
}
} while(true);
fw.close();
}catch(IOExceptione){
System.out.println(e);
}
}
}
BufferedReader#readLine does not return null
as long as the input state persists.
If you do not enter a string and line feed, return the empty string" instead of null
.
コメント As you can see in the comments, "After that, enter a new line (press enter at the beginning of the line)" and "enter a blank character (press space at any position)" have different meanings, but we have decided that the former is looking for behavior.
sample code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class TextOuter {
public static void main(String[]args) {
try{
BufferedReader buff = new BufferedReader (new InputStreamReader (System.in));
File file=new File("out/kadai8_01.txt");
FileWriter fw = new FileWriter(file);
String line;
while((line=buf.readLine())!=""){
fw.write(line);
}
buf.close();
fw.close();
} catch(IOExceptione){
System.out.println(e);
}
}
}
© 2024 OneMinuteCode. All rights reserved.