Java-File

  • Read stdin
    • import java.util.Scanner
    • Scanner in = new Scanner(System.in);
    • data a = in.nextData(primitive type/ Wrapper class data)
      • read String: in.next();(white space delimiter)
      • read whole line as a String: in.nextLine():(enter delimeter)
      • transfer data:
        • exp. String -> int : Integer.parseInt(String)
  • Read from file
    • File inputFile = new File(“fileName”)
    • Scanner in = new Scanner(inputFile)
    • then use Scanner method nextData()/hasData()
    • add in.close by the end of project
  • Output to File
    • PrintWriter out = new PrintWriter (“out.txt”)
      • if out.txt exist, it will clear to blank
      • if not, it will been create
    • out.print/out.println/out.printf
    • add out.close by the end of project
  • Exception
    • for input: “FileNotFindException”
    • for output: User may not allowed to create or overwrite the file in given location
    • throw exception in function
    • when use a path to find file, use two \ instead of one to seperate each level
      • exp. d:\\cmpt270\\out.txt
      • single\+specific character = escape character
        • exp.\n line seperate

留下评论