Java读取换行符

时间:2013-12-11 03:53:58

标签: java file file-io linefeed

我正在尝试从包含\n的字符串编写的文本文件中读取数据。结果,这些字符被写为换行符。当我试图回读时,

我正在使用FileInputStreamInputStreamReaderBufferedReader。但是,当我读入每一行时,阅读器会注意换行并将其计为行尾。 我真正想要的是阅读到行尾,保留换行符。我试图在创建文件时看看我是否真的能够写出\n字符,但无论我尝试什么,他们都不会在不转换为正常换行符的情况下编写。

如何在保留换行符的同时读取此文件?

编辑:为了便于说明,以下是我正在阅读的数据示例。可见,每行Args都在其自己的行上。这是我想忽略的换行符。我希望每个命令(例如dt,e,b,c,o等)拥有它自己的行。理想情况下,这将是这样的:

o Desc: Opens a file or folder#Args: [<handle or path>] -- the path of the file or folder#(<file name>) -- the name of the file to open. Omit if you are opening a folder.

我用#符号替换了我想忽略的换行符。但是,当我将文件读回我的程序时,我希望它是这样的,如果我System.out.println();该行,那么已被#替换的换行符将正确显示。

dt Desc: Toggles the state of debug mode.
e Desc: Exits QuiConsole
b Desc: Goes to the specified webpages.
    Args: [<URLs>] -- the URLs of the webpages to visit, separated by spaces
c Desc: Clears the console window.
o Desc: Opens a file or folder
    Args: [<handle or path>] -- the path of the file or folder
          (<file name>) -- the name of the file to open. Omit if you are opening a folder
l Desc: Searches the web
    Args: [<query>] -- the query to search for
h Desc: Displays a list of all the current handles.
    Args: (<handle names>) -- displays information for only the specified handles.
info Desc: Displays information about QuiConsole
help Desc: Displays a list of all commands, their descriptions and their arguments, if any exist.
    Args: (<command names>) -- Displays information for the specified command only. Ignores any invalid command names.
s Desc: Shuts down, restarts, hibernates or logs off the computer.
    Args: [s,r,h,l] -- shuts down, restarts, hibernates or logs off the computer respectively.
          (<integer value>) -- the number of seconds to delay the action.
dh Desc: Deletes all handles
    Args: (<handle names>) -- deletes only the specified handles
r Desc: Runs the specified program
    Args: [<names>] -- the names of the programs to run. Separate programs by a space.
wa Desc: Displays the answer from Wolfram|Alpha
    Args: [<query>] -- the query to send to Wolfram|Alpha
ch Desc: Modifies a handle
    Args: [<handle names>] -- the handle to change
          [<new value>] -- the new value to assign to the handle
ah Desc: Adds the specified handles.
    Args: [handle] -- name of the handle.
          [value] -- value for the handle
ds Desc: Displays the state of debug mode.
dhist Desc: Deletes command history

2 个答案:

答案 0 :(得分:0)

  

我试着看看我是否真的能写出字符\和n

你可以,但这不构成换行符。换行符是CR(0x0d),LF(0x0a)或CRLF(0x0d0a)之一。 \r是CR中字符和字符串文字的Java 转义。它不会出现在输出文件中。类似地,\n是字符和字符串文字中LF的Java转义。

您必须使用readLine()读取您的文件 not ,直到您遇到'\ r','\ n'或'\ r \ n',将其视为Java转义序列,而不是文字字符。

但在我看来,你真正想做的只是读取行,并将以空格开头的行追加到前一行,而不是将它们视为新行。

答案 1 :(得分:0)

我最终没有读到换行符。相反,我最终将我的HashMap对象写入文件。