斩月sama 2015-04-16 10:21 采纳率: 66.7%
浏览 1796
已采纳

如何理解这个java程序

package exercise_9;
import java.util.*;
import java.io.*;

public class Exercise9_16 {
/**Main method*/
public static void main(String[] args) throws Exception {
// Check command line parameter usage
if (args.length != 1) {
System.out.println(
"Usage: java Exercise9_16 filename");
System.exit(0);
}

// Check if source file exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
   System.out.println("Source file " + args[0] + " not exist");
   System.exit(0);
}

StringBuilder buffer = new StringBuilder();
Scanner input = new Scanner(sourceFile);

while (input.hasNext()) {
  String s = input.nextLine();//一行行输入
  String s1 = s.trim();//把多出来的空格都删掉
  System.out.println(s1);
  if (s1.charAt(0) == '{') {
    buffer.append(" {");
    if (s1.length() > 1) buffer.append("\r\n" + s.replace('{', ' '));
  }
  else
    buffer.append("\r\n" + s);
}

input.close();

// Write buffer into the file
PrintWriter output = new PrintWriter(sourceFile);
output.print(buffer.toString());
output.close();

}
}


  • 写回答

6条回答 默认 最新

  • qq_22002307 2015-04-16 12:23
    关注

    package exercise_9;
    import java.util.*;
    import java.io.*;

    public class Exercise9_16 {
    /**Main method*/
    public static void main(String[] args) throws Exception {
    // Check command line parameter usage
    if (args.length != 1) //判断输入的参数是否是一个, 如果不是,则打印下面信息
    System.out.println(
    "Usage: java Exercise9_16 filename");
    System.exit(0); //然后退出程序
    }

    // Check if source file exists
    File sourceFile = new File(args[0]); //创建一个以参数名为文件名的文件
    if (!sourceFile.exists()) { // 判断文件是否存在 ,如果不存在 则打印一下信息 ,退出程序
    System.out.println("Source file " + args[0] + " not exist");
    System.exit(0);
    }

    StringBuilder buffer = new StringBuilder(); // 创建一个字符串容器
    Scanner input = new Scanner(sourceFile); //扫描文件

    while (input.hasNext()) { //判断文件内容是否存在,
    String s = input.nextLine();//一行行输入 //把文件内容读入 s 字符串中
    String s1 = s.trim();//把多出来的空格都删掉 //把s字符串中的空格去掉
    System.out.println(s1); // 打印s1
    if (s1.charAt(0) == '{') { // 判断字符串s1中第一个字符是否为‘{’
    buffer.append(" {"); // 如果是 ,则向字符串容器中添加 ‘{’
    if (s1.length() > 1) buffer.append("\r\n" + s.replace('{', ' ')); // 如果s1的长度大于1, 则向字符串容器中添加换行及下行首位置,把s里‘ 用‘{换
    }
    else
    buffer.append("\r\n" + s); // 否则buffer字符串容器添加换行 及首位置, s字符串
    }

    // Write buffer into the file
    PrintWriter output = new PrintWriter(sourceFile); // 输出流 把先前的文件 连接一条管道 即输出流
    output.print(buffer.toString()); // 输出buffer容器里的字符
    output.close();
    }
    }

    希望对你有帮助 ,谢谢

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算