文件操作
Posted zoute
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件操作相关的知识,希望对你有一定的参考价值。
package 文件操作; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; public class FileOption { String filename = "C:\Users\Administrator\Desktop\新建文件.txt"; String inputname; int selectnum = 0; public FileOption() { Scanner scanner = new Scanner(System.in); System.out.println("请输入文件地址:"); inputname = scanner.nextLine(); System.out.println("请输入你的选择:" + "1:创建文件" + "2:删除文件" + "3:读取文件" + "4:写入文件"); selectnum = scanner.nextInt(); while(true) { switch (selectnum) { case 1: CreateFile(inputname); selectnum = scanner.nextInt(); break; case 2: DeleteFile(inputname); selectnum = scanner.nextInt(); break; case 3: ReadFile(inputname); selectnum = scanner.nextInt(); break; case 4: WriteFile(inputname); selectnum = scanner.nextInt(); break; default: break; } } // DeleteFile(filename); // ReadFile(filename); } private void CreateFile(String Filename) { File file = new File(Filename); try { if(!file.exists()) { file.createNewFile(); } } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } private void DeleteFile(String DeleteFile) { File file = new File(DeleteFile); if(file.exists()) { file.delete(); } } private String ReadFile(String ReadFile) { File file = new File(ReadFile); String data = null; char buff[] = new char[1024]; try { FileReader fileReader = new FileReader(file); fileReader.read(buff); data = new String(buff); System.out.println("读取到:"+data); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return data; } private void WriteFile(String Writedata) { File file = new File(Writedata); try { PrintStream ps = new PrintStream(file); ps.append("我是新写入的文件内容 "); } catch (FileNotFoundException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } }
}
//主函数部分 package 文件操作; public class Main { public static void main(String[] args) { // TODO 自动生成的方法存根 new FileOption(); } }
以上是关于文件操作的主要内容,如果未能解决你的问题,请参考以下文章