
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.使用FileInputStream,从文件读取数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import java.io.*;
public class TestFileImportStream {
public static void main(String[] args) {
int b=0;
FileInputStream in = null ;
try {
in = new FileInputStream( "C:\\Users\\41639\\Desktop\\java\\FileText\\src\\TestFileImportStream.java" );
} catch (FileNotFoundException e){
System.out.println( "file is not found" );
System.exit(-1);
}
try {
long num=0;
while ((b= in .read())!=-1) {
System.out.println((char)b);
num++;
}
in .close();
System.out.println();
System.out.println( "共读取了" +num+ "个字节" );
} catch (IOException e) {
System.out.println( "IO异常,读取失败" );
System.exit(-1);
}
}
|
2.字符流便捷类
Java提供了FileWriter和FileReader简化字符流的读写,new FileWriter等同于new OutputStreamWriter(new FileOutputStream(file, true))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class IOTest {
public static void write(File file) throws IOException {
FileWriter fw = new FileWriter(file, true );
String string = "松下问童子,言师采药去。只在此山中,云深不知处。" ;
fw.write(string);
fw.close();
}
public static String read(File file) throws IOException {
FileReader fr = new FileReader(file);
char[] chars = new char[1024];
StringBuilder sb = new StringBuilder();
int length;
while ((length = fr.read(chars)) != -1) {
sb.append(chars, 0, length);
}
fr.close();
return sb.toString();
}
}
|
3.使用缓冲区从键盘上读入内容
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static void main(String[] args) throws IOException {
BufferedReader buf = new BufferedReader(
new InputStreamReader(System. in ));
String str = null ;
System.out.println( "请输入内容" );
try {
str = buf.readLine();
} catch (IOException e){
e.printStackTrace();
}
System.out.println( "你输入的内容是:" + str);
}
|
以上就是IO流在java中的实例操作,涉及到File类、字符流、缓冲流的知识点。对于这方面基础知识不够牢固的,可以在以往的内容中重新学习,然后进行实例的操作。