基本上,“{”和“}”需要位于新行上才能输出。但我不知道如何有效地读取某些字符。我有一个程序可以读取行并输出它们,但不知道从哪里开始。谢谢
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
try {
FileReader reader = new FileReader("textfile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
这是一个简单的方法(使用 org.apache.commons.io 进行文件解析):
解决方案
public static void main(String args[]) throws IOException {
File testFile = new File("textfile.txt");
String fileContent = FileUtils.readFileToString(testFile);
fileContent = fileContent.replaceAll("\\{", "\n{").replaceAll("}", "\n}");
System.out.println(fileContent);
}
说明
这会将文件读取为字符串,并相应地将所有出现的 '{' 或 '}' 替换为 '\n{' 或 '\n}'。
顺便说一句。只有 '{' 字符需要通过 '\\' 进行分隔。
编辑:
如何使用该库。
看来您是 Java 新手,要使用该库您有多种选择。其中之一是使用项目管理工具,例如“Apache Maven”。
然而,最简单的选择是 donwload the library (选择“commons-io-2.4-bin.zip”)。
将文件commons-io-2.4.jar解压到您的项目中。假设您有一个现代 IDE,它会知道如何在代码中使用库时导入该库。
关于 java ;文件输入输出中特定字符的换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33720025/