如何切换/切换文本文件中每个字母的大小写?

时间:2015-02-22 19:24:15

标签: java switch-statement toggle uppercase lowercase

好的,这是我为程序创建的代码,用于读取文本文件。 现在有人可以告诉我如何将结果中的每个字母的大小写从大写切换到更低,反之亦然?请注意,我希望程序从命令行读取文件,而不是字符串 如果可能,我希望代码中的答案:|由于
我是Java的新手,可以使用一些帮助谢谢。

public class Main {

        /**
        * @param args the command line arguments
        */
        public static void main(String[] args) {
        // TODO code application logic here
         java.io.File file = new           java.io.File("C:\\Users\\Lifeless\\Desktop\\123.txt");

        try {
        Scanner input = new Scanner(file);
        while (input.hasNext()) {
        String num = input.nextLine();  //grabs line
        System.out.println(num);
        }
        }
        catch (FileNotFoundException e) {
        System.err.format("File does not exist \n");

1 个答案:

答案 0 :(得分:0)

我使用了bufferedReader并将文件的所有行放在ArrayList中。

static ArrayList<String> lines;
  public static void main(String[] args) throws FileNotFoundException, IOException
  {
    lines = new ArrayList<>();
    File f = new File(args[0]);
    BufferedReader r = new BufferedReader(new FileReader(f));

    String line = r.readLine ();
    while(line != null)
    {
      lines.add(invert(line));
      line = r.readLine ();
    }
    for(String  s : lines)
    {
      System.out.println(s);
    }
  }

  private static String invert(String line)
  {
    char[] singleChars = line.toCharArray (); //split Line into single Characters
    for(int i = 0;i< singleChars.length;i++) //Iterate over every single Character
    {
      if(Character.isAlphabetic (singleChars[i]))
      {
        if(Character.isUpperCase (singleChars[i])) //swap Upper to Lower and vice versa
        {
          singleChars[i] = Character.toLowerCase (singleChars[i]);
        }else
        {
          singleChars[i] = Character.toUpperCase (singleChars[i]);
        }
      }
    }
    return new String(singleChars);
  }