输入输出:
控制台输入输出:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.printf("Enter escape character: "); String s; try { s = br.readLine(); char escaper = s.length() > 0 ? s.toCharArray()[0] : 'q'; System.out.printf("Escape character %c", escaper); char c; do { c = (char)br.read(); if (c != '\r' && c != '\n') { System.out.printf("You have entered %c\r\n", c); } } while (c != escaper); } catch (IOException e) { e.printStackTrace(); } |
Scanner读取控制台输入:
// example 1 Scanner scanner = new Scanner(System.in); while (true) { if (!scanner.hasNext()) { break; } String input = scanner.next(); System.out.println(input); } scanner.close();
// example 2 Scanner scanner = new Scanner(System.in); while (true) { if (!scanner.hasNextLine()) { break; } String input = scanner.nextLine(); System.out.println(input); } scanner.close(); // next()以空白字符作为输入的分割,所以无法获取带有空格的字符串 // nextLine()以换行符作为输入结束,能够获得带有空格的字符串
Scanner scanner = new Scanner(System.in); for (int i = 0; i < 10; i++) { if (scanner.hasNextBoolean()) { System.out.printf("Entered boolean: %b", scanner.nextBoolean()); } if (scanner.hasNextInt()) { System.out.printf("Entered int: %d", scanner.nextInt()); } if (scanner.hasNextDouble()) { System.out.printf("Entered double: %f", scanner.nextDouble()); } } scanner.close(); |
文件读写:
try { File fin = new File("C:\\Users\\DanielHX\\Desktop\\Demo.txt"); InputStream sin = new FileInputStream(fin); InputStreamReader sr = new InputStreamReader(sin);
File fout = new File("C:\\Users\\DanielHX\\Desktop\\Demo_Copy.txt"); FileOutputStream sout = new FileOutputStream(fout); OutputStreamWriter sw = new OutputStreamWriter(sout, "UTF-8");
BufferedReader br = new BufferedReader(sr); String line = br.readLine(); while (line != null) { System.out.println(line); sw.append(line); sw.append("\r\n"); line = br.readLine(); }
sr.close(); sin.close(); sw.close(); sout.close(); } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e1) { System.out.println("Error when reading/writing from file"); } |
目录操作:
// mkdir will create a sub folder, if parent folder doesn't exist, // or this sub folder exists, will return false String dir = "d:\\test"; File d = new File(dir); d.mkdir(); String dir1 = "d:\\test\\sub1\\sub2\\sub3\\sub4"; File d1 = new File(dir1); d1.mkdirs(); printSubFolder(dir);
// only works if the directory is empty d.delete();
PrintSubFolder: public void printSubFolder(String dir) { File f = new File(dir); String[] paths = f.list(); System.out.printf("Sub folder %s\r\n", dir); for (String s : paths) { String path = dir + "\\" + s; File subDirOrFile = new File(path); if (subDirOrFile.isDirectory()) { printSubFolder(path); subDirOrFile.delete(); } } } |