简单的文件读写程序 求助,新手遇到问题
小芈 2015-03-18 09:03:07 练习题,编写一个文件读写的程序,我想问问各位大牛,怎样在每个方法里再调用menu 方法,还有文件读写的参数传递应该怎么设置?附上源码,略粗糙,不胜感激!
import java.io.*;
import java.util.Scanner;
/**
* Created by Guodada on 15/3/18.
*/
public class FileTest {
public static void main(String [] args) throws IOException {
FileTest test1 = new FileTest() ;
test1.menu(test1);
}
public static void menu(FileTest test1) throws IOException {
File file = null,file1 = null;
String book = new String();
FileTest test = new FileTest();
System.out.println("请选择要执行的操作: 1.创建目录 2.创建文件 3.输入图书信息 4.导入图书信息 5.查看图书信息 0.退出");
int choice = 0;
Scanner scan = new Scanner(System.in);
choice = scan.nextInt();
switch (choice){
case 0:System.exit(0);
break;
case 1:test.CreateFolder(file);
break;
case 2:test.CreateFile(file1);
break;
case 3:test.InputBook();
break;
case 4:test.OutFile(file1, book);
break;
case 5:test.ReadFile(file1);
break;
default:System.out.println("输入信息错误!");
return;
}
}
public File CreateFolder(File file) throws IOException {
String str = new String();
Scanner scan = new Scanner(System.in);
System.out.println("请输入目录的路径:");
str = scan.next();
file = new File(str);
String folder[];
folder=file.list();
if (!file .exists() && !file .isDirectory()) //判断目录是否存在
{
System.out.println("目录不存在,创建目录!");
file.mkdirs();
System.out.println(file.getName()+"目录创建成功!");
}
else {
System.out.println("目录存在,请在目录后输入文件名:");
for(int i=0;i<folder.length;i++)
{
System.out.println(folder[i]);
}
CreateFile(file); //新建文件
}
return file;
}
public File CreateFile(File file) {
String str = new String();
Scanner scan = new Scanner(System.in);
System.out.println("请输入文件名称:");
str = scan.next();
File file1 = new File(str);
if(file1.exists()){
//判断文件是否存在
System.out.println(file.getName());
}
else {
/**try {
file1.createNewFile();
System.out.println(file1.getName());
} catch (IOException e) {
e.printStackTrace();
}*/
file1.mkdirs();
System.out.println(file1.getName()+"文件创建成功!");
}
return file1;
}
public String InputBook() { //输入图书信息
System.out.println("分别录入图书名称,出版社,价格,数量,是否教材(True or False)");
String book = new String();
Scanner scan = new Scanner(System.in);
book = scan.next();
System.out.println("是否结束录入图书信息? Y/N");
return book;
}
public File OutFile(File file1, String str) throws IOException {
str = new String();
File file = null; //将图书信息写入文件
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(str);
bw.flush();
bw.close();
System.out.println("图书信息已经写入文件!");
return file;
}
public File ReadFile(File file1) throws IOException {
File file = null; //从文件中读出图书信息
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(true){
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
}
if(line == null){
break;
}
System.out.println(line);
}
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}