代码:
import com.sun.beans.editors.ByteEditor;
import java.io.*;
import java.util.Scanner;
class Test
{
private static String filename;
private static File f;
Test(String filename){
this.filename=filename;
}
static void open(){
f = new File(filename);
if(f.exists()){
System.out.println("文件已经存在");
}
else{
try{
System.out.println("该文件不存在,新建文件");
f.createNewFile();
}
catch (IOException e){
System.out.println(e.getMessage());
System.out.println("创建失败");
}
}
}
void Show(){
System.out.println("绝对路径"+f.getAbsoluteFile());
System.out.println("文件名"+f.getName());
System.out.println("路径"+f.getPath());
}
void List(String list_name){
File f2 = new File(list_name);
String[] all_result = f2.list();
for(String s : all_result)
System.out.println(s);
}
void Delete(){
f.delete();
}
void Input(){
byte[] b = new byte[1024];
int n = -1;
try {
FileInputStream in = new FileInputStream(f);
while((n=in.read(b))!=-1){
String s = new String(b);
System.out.println(s);
}
in.close();
}catch (IOException e){
System.out.println("读取文件错误");
}
}
void OutPut(String content){
byte[] b = content.getBytes();
try{
FileOutputStream out = new FileOutputStream(f);
out.write(b);
out.close();
System.out.println("文件写入成功");
}catch (IOException e){
e.printStackTrace();
}
}
void AppendMethod(String content) {
try {
FileWriter writer = new FileWriter(f, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class c {
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入文件名");
String filename = sc.nextLine();
Test t = new Test(filename);
t.open();
t.Show();
t.OutPut("Java");
t.Input();
t.AppendMethod("123");
t.Input();
t.Delete();
t.List("C:\\");
}
}
运行结果