JavaIO读写操作

java 创建文件并写入

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
30
31
32
33
/*
* Create by vampire. 2017/5/8
*/
//This code for creat a file and write it.
// First we import java class.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class DemoJava {
public static void main(String[] args){
try {//
File file=new File("fileName.txt");//Create .txt file using File class
if(!file.exists()){//check fileName.txt whether exist
file.createNewFile();
}
PrintWriter pw=new PrintWriter(file);
pw.println("This is my file content:");
pw.println(10000000);
pw.close();
System.out.println("Done successfully!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

java 读取文件实例

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
// import java class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class JavaRead {
public static void main(String[] args){
BufferedReader br=null;//initialize
try{
br=new BufferedReader(new FileReader("fileName.txt"));
String line;
while((line=br.readLine())!=null){
System.out.println(line);//read by line
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
br.close();//close
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
您的支持将鼓励我继续向前!