有 Java 编程相关的问题?

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

如何在Java中使用递归和流从文件中输出字符串行

sldls slfjksdl slfjdsl
ldsfj, jsldjf lsdjfk

这些字符串行来自一个名为“input”的文件

如何使用Java中的输入、输出流和递归,将这些字符串行以相反的顺序输出到名为“ouput”的文件中


共 (1) 个答案

  1. # 1 楼答案

    我不打算把整个代码放在这里,但我会把每个关键领域的部分放在一起,希望你们能把所有东西放在一起

    下面是如何反转给定字符串

    public static String reverseString(InputStream is) throws IOException {
     int length = is.available();
     byte[] bytes = new byte[length];
     int ch = -1;
     while ((ch = is.read()) != -1) {
      bytes[ length] = (byte) ch;
     }
     return new String(bytes);
    }
    

    这就是调用上述函数的主要方法

    InputStream is = new FileInputStream(f);
    String reversedString = reverseString(is);
    

    最后,希望你能通过玩这个来了解如何写入文件

      try{
      // Create file 
      FileWriter fstream = new FileWriter("/Users/anu/GroupLensResearch/QandA/YahooData/L16/out.txt");
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(reverseRead(is));
      //Close the output stream
      out.close();
      }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
      }