[英]reading single quotes from text file in java using BufferedReader
[英]Reading single backslash from a text file using java code
關於此的文章很多,每個人都建議更改文本文件的內容。 我在這里的要求是,我正在解析一個c ++源文件。 在解析期間,當我在結尾處找到反斜杠時,可能需要將多行合並在一起。 示例:char line [100] =“ hello加入多行。\\
哦,不要問我編輯CPP源文件。”
如何從xyz.cpp文件中讀取此文本,並弄清楚該行的末尾有反斜杠。 我使用FileInputReader逐行讀取,但是當我在Java中獲取該行時,反斜杠丟失了。
希望您不要建議我更改CPP源代碼以將\\替換為\\
提前致謝。
反斜杠是Java中的轉義字符。 因此,如果要與真實的反斜杠- \\
匹配,則必須尋找\\\\
。
您可以將contains()
或indexOf()
用於字符串文字。
或逐字閱讀並檢查條件:
if (c == '\\\\')
希望這可以幫助!
在最簡單的級別上,您可以通過換行符分割文件數據( data.split('\\n')
,其中data
是String
),然后檢查它是否以反斜杠結尾( line.endsWith('\\\\')
,其中line
是一個String
)
以下代碼加載文件並打印每一行
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String args[]) throws Exception{
Scanner scan = new Scanner(new File("file.txt"));
scan.useDelimiter("\\Z");
String content = scan.next();
String[] lines = content.split("\n");
for (String value : lines) {
System.out.println(value);
}
}
}
我創建了一個包含以下幾行的文件“ file.txt”
line 1
line 2\
line 2cnt
line 3
代碼將輸出
line 1
line 2\
line 2cnt
line 3
要加入這些行,您可以運行以下代碼
public static void main(String args[]) throws Exception{
Scanner scan = new Scanner(new File("file.txt"));
scan.useDelimiter("\\Z");
String content = scan.next();
String[] lines = content.split("\n");
for (String value : lines) {
if (value.endsWith("\\")) {
value = value.substring(0, value.length()-1);
System.out.print(value);
} else {
System.out.println(value);
}
}
}
將輸出
line 1
line 2line 2cnt
line 3
根據您的評論進行編輯:
public static void main(String args[]) throws Exception {
FileInputStream fileInputStream = new FileInputStream("file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
輸出
line 1
line 2\
line 2cnt
line 3
和
public static void main(String args[]) throws Exception {
FileInputStream fileInputStream = new FileInputStream("file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
String line;
while ((line = reader.readLine()) != null) {
if (line.endsWith("\\")) {
line= line.substring(0, line.length()-1);
System.out.print(line);
} else {
System.out.println(line);
}
}
}
輸出
line 1
line 2line 2cnt
line 3
不確定,為什么在計算機上看不到反斜杠。 您可以發布完整的代碼和文件內容嗎? 您在什么平台上運行它? 文件的編碼是什么? 也許您需要像這樣將編碼傳遞給InputStreamReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
這是Eclipse IDE的編譯問題,我重新啟動了Eclipse並進行了干凈的編譯。 現在,一切都按預期進行。 謝謝你們的時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.