写入文件后可逆序输出
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.io.*;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
//创建文件对象
File file= new File("2.txt");
if (file.exists()) {
//文件存在
String name= file.getName();
long len= file.length();
//判断文件隐藏属性
boolean hidden= file.isHidden();
System.out.println("文件名称: "+ name+ "\n文件长度: "+ len+ "\n隐藏属性: "+ hidden);
writefile(file);
readfile(file);
}else {
//文件不存在,创建文件
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
System.out.println("文件已创建");
}
}
}
private static void readfile(File file) {
// TODO Auto-generated method stub
try {
FileInputStream fileInputStream= new FileInputStream(file);
byte[] b= new byte[1024];
int len= fileInputStream.read(b);
fileInputStream.close();
StringBuilder ab = new StringBuilder(new String(b, 0, len));
System.out.println("文件读出的内容是: \n"+ ab.reverse().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void writefile(File file) {
// TODO Auto-generated method stub
Scanner in= new Scanner(System.in);
System.out.println("请输入要写入得内容");
String string= in.next();
//建立文件传输管道
try {
FileOutputStream fileOutputStream= new FileOutputStream(file);
//写文件
fileOutputStream.write(string.getBytes());
//关闭管道
fileOutputStream.close();
System.out.println("文件写入完成");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your support will encourage me to continue to create!