读取
读取有两种方法:
1)使用Scanner类
2)BufferedReader和InputStreamReader组合使用
Scanner定义在java.util包中,要在程序import java.util.Scanner 。Scanner类中的方法有:
- Scanner(InputStream in)用给定输入流创建Scanner对象
- Scanner(InputStream in, String charsetName )用给定输入流和编码格式创建Scanner对象
- Scanner(File f)构造一个从给定文件读取数据的Scanner对象
- string nextLine()读取输入的下一行内容
- string next()读取输入的下一个单词(以空格为分割符)
- int nextInt()读取并转换的下一个表示整型的字符序列
- double nextDouble()读取并转换下一个表示浮点型的字符序列
- boolean hasNext()检测输入中是否还有其他单词
- boolean hasNextLine()检测是否有下一行
- boolean hasNextInt()检测是否还有表示整数的下一个字符序列
- boolean hasNextDouble()检测是否还有表示浮点数的下一个字符序列
- 。。。
BufferedReader中与Scanner相似的方法有:
- BufferedReader(InputStream in)用给定输入流创建BufferedReader对象
- string readLine()读取输入的下一行内容
- int read()得到输入第一位对应的Ascii码!!!!
可以看到,Scanner比BufferedReader的方法更丰富
读取输入
使用scanner类:
例子:
Scanner in=new Scanner(System.in);
System.out.print("what is your name?");
String name=in.nextLine();
System.out.println("hello,"+name);
in.close();
注:更安全的方式应该使用try catch或者throw IOException的方式处理异常。见下面的例子
使用BufferedReader和InputStreamReader:
InputStreamReader和BufferedReader包含在java.io中,需要import java.io.*。
例子:
try{
InputStreamReader isr=new InputStreamReader(System.in,"UTF-8");
BufferReader input=new BufferReader(isr);
System.out.print("what is your name?");
String name=input.readLine();
input.close();
isr.close();
}catch (IOException e){
e.printStackTrace();
}
读取文件
使用scanner类:
例子:
String filename="/home/thinkit/Documents/filtered_test5.txt";
try{
Scanner in=new Scanner(Paths.get(filename));//不写编码格式默认跟随系统的编码格式
while(in.hasNextLine()){
String str=in.nextLine();
println(str);
}
in.close();
}catch (IOException e){
e.printStackTrace();
}
注:static Path get(String pathname)根据给定的路径构造一个Path
使用BufferedReader和InputStreamReader:
String filename="/home/thinkit/Documents/filtered_test5.txt";
try{
InputStreamReader isr=new InputStreamReader(new FileInputStream(new File(filename)),"UTF-8");
BufferReader input=new BufferReader(isr);
while(input.readLine()!=null){
String str=input.readLine();
println(str);
}
input.close();
isr.close();
}catch (IOException e){
e.printStackTrace();
}
写文件
写文件同样有2种方法:
1)使用PrintWriter
2)OutputStreamWriter和BufferdWriter组合使用
用PrintWriter
写文件需要构造一个PrintWriter对象,在java.io.PrintWriter包中。构造文件之后可以像输出到System.out一样使用print,println以及printf命令写入到文件中。
例子:
String filename="/home/thinkit/Documents/file.txt";
try{
PrintWriter out=new PrintWriter(filename);//不写编码格式默认跟随系统的编码格式
out.println("hello world!");
out.close();
} catch (IOException e){
e.printStackTrace();
}
用OutputStreamWriter和BufferdWriter
OutputStreamWriter和BufferdWriter包含在java.io库中。
例子:
String filename="/home/thinkit/Documents/file.txt";
OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(new File(filename)) ,"utf8");
BufferedWriter bw=new BufferedWriter(osw);
try {
bw.write("hello!");
}catch (IOException e){
e.printStackTrace();
}
bw.close();
osw.close();
其实,上面直接使用osw.write()也可以写入,效果与bw相同。
查阅网上的资料,发现在速度上两种读写方法并没有太大区别,但是在使用上Scanner和PrintWriter更为方便。