有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

BufferedReaderJava;使用文件输入为输出中的特定字符换行

基本上,{和}需要在输出的新行上。但我不知道如何有效地阅读某些字符。我有一个程序,读取并输出这些行,但不知道从哪里开始。谢谢

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();
  }
}

共 (3) 个答案

  1. # 1 楼答案

    您可以使用String.replaceAll方法,然后可以添加新行并将{打印到新行

    以下是您如何做到这一点:

     public static void main(String[] args) throws IOException {
           try {
            FileReader reader = new FileReader("textfile.txt");
            BufferedReader bufferedReader = new BufferedReader(reader);
    
            String line;
    
    
    
    
    
            while ((line = bufferedReader.readLine()) != null) {
             line=line.replaceAll("\\{", "\n{");
             line=line.replaceAll("\\}", "\n}");
                System.out.println(line);
            }
            reader.close();
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
  2. # 2 楼答案

    正如您希望读取文件字符一样。不要读行,而是读字符

    while ((r = reader.read()) != -1) {
                char ch = (char) r;
               // do your work
            }
        }
    

    若你们因为某种原因想先读一行 一个你接电话

    char[] chars = line.toCharArray();
    for (Char char : chars)
    {
        // check for that character and process accordingly
    }
    
  3. # 3 楼答案

    下面是一种简单的方法(使用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新手,要使用该库,您有多种选择。其中之一是使用项目管理工具,如“ApacheMaven”

    然而,最简单的选择是donwload the library(选择“commons-io-2.4-bin.zip”)

    提取文件commons-io-2.4。将jar添加到您的项目中。假设您有一个现代化的IDE,它将知道在代码中使用该库时如何导入该库