java中如何表示一个回车符

Python018

java中如何表示一个回车符,第1张

可以使用Java中\n和\r的换行,不过也是有区别的,如下:1.\r 叫回车 Carriage Return2.\n 叫新行 New Line但是都会造成换行,使用System.getProperty("line.separator")来获取当前OS的换行符java 代码 1. String userInputString = userInput 2. userInputString = userInputString.replaceAll ( "\r", "" ) 3. userInputString = userInputString.replaceAll ( "\n", "\\\\"+System.getPropert("line.separator"))

\r回车是将光标移到一行的前面

\n是移到下一行

一句一句给你分析

1代表光标位置

System.out.print("a")

输出:

a1

System.out.print("\n")

输出:

a

1

System.out.print("b")

a

b1

System.out.print("\r")

a

1b

注意,在这里,回车将光标移动到了b前面,所以下一个输出c时b将被替换

System.out.print("c")

a

c1

下面相同

自己分析吧

Java中可以用PrintWriter对象操作文件流写入记事本,这个对象有一个方法println()自动换行,测试代码如下:

package com.zzl

import java.io.File

import java.io.FileWriter

import java.io.PrintWriter

import java.io.IOException

public class FileEnter {

        public static void main(String[] args) throws IOException{

                String str1="abc"

                String str2="def"

                File file=new File("D:\\abc.txt")

                FileWriter fw=null

                PrintWriter out=null

                try{

                fw=new FileWriter(file)

                out=new PrintWriter(fw)

                out.println(str1)

                out.println(str2)

                

                }catch(IOException e){

                        System.out.println(e.getMessage())

                }finally{

                        out.close()

                        fw.close()

                }

        }

}