在java的IO中,如何通过控制台向某txt文件中输入字符串后自动换行。以下是我写的,无法实现换行。
请大家帮帮忙,初学者,着急用,谢谢了。publicvoidwrite()throwsException{InputStreamin=System.in;InputStre...
请大家帮帮忙,初学者,着急用,谢谢了。
public void write()throws Exception{
InputStream in=System.in;
InputStreamReader r1=new InputStreamReader(in);
BufferedReader br1=new BufferedReader(r1);
String s=br1.readLine();
FileOutputStream fos=new FileOutputStream(fileName,true);
try{
byte[] data=s.getBytes();
fos.write(data);
fos.flush();
}finally{
fos.close();
} 展开
public void write()throws Exception{
InputStream in=System.in;
InputStreamReader r1=new InputStreamReader(in);
BufferedReader br1=new BufferedReader(r1);
String s=br1.readLine();
FileOutputStream fos=new FileOutputStream(fileName,true);
try{
byte[] data=s.getBytes();
fos.write(data);
fos.flush();
}finally{
fos.close();
} 展开
2个回答
展开全部
第一,String s=br1.readLine()变String s=br1.readLine()+"\n";
注意的是,在Linux系统中是"\n",但是在Windows中建议用"\r\n",这样在记事本里看才有换行
\r 是换行符
\n 是回车符
第二,或者用PrintWriter:
import java.io.PrintWriter;
import java.io.File;
public class Testing{
public static void main(String[] args){
File file =new File("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter =new PrintWriter(file);
printWriter.println ("hello");
printWriter.close ();
}
}
同时,使用Scanner进行输入:
import java.util.Scanner;
classTestRevised{
public static String input(){
Scanner scanner =new Scanner(System.in);
System.out.print("Enter text:\t");
String sentence = scanner.nextLine(); // 你可以使用循环判断,当sentence.lenght=0时结束输出
}
}
public static void main(String[] args) {
try {
File file =new File("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter =new PrintWriter(file);
Scanner scanner = new Scanner(System.in);
String line = "\0";
while(line.length>0) {
line = scanner.nextLine();
printWriter.println(line);
}
printWriter.close ();
}
catch(Exception e) {}
}
注意的是,在Linux系统中是"\n",但是在Windows中建议用"\r\n",这样在记事本里看才有换行
\r 是换行符
\n 是回车符
第二,或者用PrintWriter:
import java.io.PrintWriter;
import java.io.File;
public class Testing{
public static void main(String[] args){
File file =new File("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter =new PrintWriter(file);
printWriter.println ("hello");
printWriter.close ();
}
}
同时,使用Scanner进行输入:
import java.util.Scanner;
classTestRevised{
public static String input(){
Scanner scanner =new Scanner(System.in);
System.out.print("Enter text:\t");
String sentence = scanner.nextLine(); // 你可以使用循环判断,当sentence.lenght=0时结束输出
}
}
public static void main(String[] args) {
try {
File file =new File("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter =new PrintWriter(file);
Scanner scanner = new Scanner(System.in);
String line = "\0";
while(line.length>0) {
line = scanner.nextLine();
printWriter.println(line);
}
printWriter.close ();
}
catch(Exception e) {}
}
来自:求助得到的回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询