功能实例
主要步骤
文件内容输入代码
Scanner scan=new Scanner(System.in);
String line="";
while(true) {
line=scan.nextLine();
if(line.equals("stop"))
break;
else
str.append(line+"\n");
其中line为输入的每个字符串模块,每个模块用回车确认,如果该模块不为stop,将其赋值给str全局变量
文件名字和路径创建
filename=new Scanner(System.in).next();
FileWriter filea=new FileWriter(filename);
String str1=str.toString();
filea.write(str1);
filea.flush();
filea.close();
filename为全局变量作为文件名包括路径,其中String str1=str.toString();的作用就是将str(文件内容)转换成Sting类型并赋值给str1,filea.write(str1);filea.flush();filea.close()这三个步骤是必须的,为了写入成功。
打开读取
String location;
System.out.print("请输入打开文件的位置:");
location=new Scanner(System.in).next();
FileInputStream fos=new FileInputStream(location);
int data;
while((data=fos.read())!=-1)
System.out.print((char)data);
实施全部代码
package university;
import java.util.*;
import java.io.*;
public class longlong {
public static StringBuffer str=new StringBuffer();
public static String filename=new String();
public static void main(String[] args) throws IOException{
menushow();
boolean xuze=true;
while(xuze)
{
switch(select())
{
case 1:newfile();break;
case 2:openfile();break;
case 3:savefile();break;
case 0:System.exit(0);break;
default:System.out.println("输入错误");
}
}
}
public static void newfile() throws IOException{
System.out.println("请输入内容,停止编写请输入stop");
Scanner scan=new Scanner(System.in);
String line="";
while(true) {
line=scan.nextLine();
if(line.equals("stop"))
break;
else
str.append(line+"\n");
}
}
public static void savefile() throws IOException{
System.out.print("请输入文件胡绝对路径:");
filename=new Scanner(System.in).next();
FileWriter filea=new FileWriter(filename);
String str1=str.toString();
filea.write(str1);
filea.flush();
filea.close();
}
public static void openfile()throws IOException
{
String location;
System.out.print("请输入打开文件的位置:");
location=new Scanner(System.in).next();
FileInputStream fos=new FileInputStream(location);
int data;
while((data=fos.read())!=-1)
System.out.print((char)data);
}
public static void menushow() {
System.out.println("******Notepad****************");
System.out.println("* 1.新建文件 *");
System.out.println("* 2.打开文件 *");
System.out.println("* 3.保存文件 *");
System.out.println("* 0.退出 *");
System.out.println("*****************************");
}
public static int select() {
System.out.print("请输入操作指令:");
int num=new Scanner(System.in).nextInt();
return num;
}
}