一. 文件的获取和写入
1. 文件的读取
File InputFile = New File(“input.txt”); //先用file类读取文件
Scanner in = new Scanner(inputFile) //接着用file的对象生成一个scanner对象
(Scanner in = new Scanner(new File(“input.txt”)); //生成scanner对象的另一种方式)
2. 文件的写入
PrintWriter out = new PrintWriter(“output.txt”);
out.println(“Hello World”);
out.printf(“Total: %8.2f\n”, total);
3. 关闭读取(Scanner)和写入(PrintWriter)的对象
in.close();
out.close();
4. 读取网页内容
String address = “http://horstmann.com/index.html”;
URL pageLocation = new URL(address);
Scanner in = new Scanner(pageLocation.openStream());
5. 输入输出流读取文件(比如图片)
URL p_w_picpathLocation = new URL(“http://horstmann.com/java4everyone/duke.gif”); //输入流
InputStream in = p_w_picpathLocation.openSream();
FileOutputStream out = new FileOutPutStream(“duke.gif”); //输出流
Boolean done = false;
while(!done){
int input = in.read();
if(input == -1){ done = true;}
else{ out.write(input); }
}
二. 文件内容的读取
1. 读一个字符(用useDelimiter方法)
Scanner in = new Scanner(…) ;
in.useDelimiter(“”);
//获取字符
while(in.hasNext()){
char ch = in.next().charAt(0);
Process ch.
}
注:分析字符类型的几个方法:isDigit(), isLetter(), isUpperCase(), isLowerCase(),isWhileSpace()
2. 读整个单词
while(in.hasNext()){
Sring input = in.next();
System.out.println(input);
}
注:next 方法读一个被while space分开的 string (while spaces 包括:spaces , tab characters和 newline characters)
如果整个文件不包含任何字符,抛出 “no such element exception”
3. 读一整行
String line = in.nextLine();
//用hasNextLine方法来判断是否有下一行可以读取
while(in.hasNextLine()){
String line = nextLine();
Process line.
}
4. 数字 单词 和行的混合读取
因为nextInt(),nextDouble() 和 next ()方法不读取(whilespace),因此在混合调用 nextInt()/nextDouble()/next() 和nextLine()方法时, 要调用nextline()方法读取换行符“/n“
例. 有下面数据:
China
1330044605
India
114995898
United Stated
3038246462
while(in.hasNextLine()){
String countryName = in.nextLine();
int population = in.nextInt();
in.nextLine();
Procees the country name and population
}
三. 内容的格式输出
格式输出需遵循的架构:第一个字符是%
选择一个标志符修改格式(可选,见表1)
规定输出的宽度
规定输出类型(见表2)
参考文献
Cay.S. Horstmann(2012). BIG JAVA Late Objects.