test098.java
package pack04;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class test098
{
private static String filePath;
private static String message = "";
public static void main(String[] args) throws Exception
{
Scanner scan1 = new Scanner(System.in);
System.out.println("--1:新建文件 2:打开文件 3:修改文件 4:保存 5:退出");
while (true)
{
System.out.println("请输入操作序号:");
int command = scan1.nextInt();
switch (command)
{
case 1:
createFile();
break;
case 2:
openFile();
break;
case 3:
editFile();
break;
case 4:
saveFile();
break;
case 5:
exit();
break;
default:
System.out.println("输入的指令错误!");
break;
}
}
}
private static void exit()
{
System.out.println("你已退出系统!");
System.exit(0); //0是正常退出,非0为异常退出
}
private static void saveFile() throws IOException
{
Scanner scan1 = new Scanner(System.in);
FileWriter out = null;
if (test098.filePath != null)
{
//文件是由打开方式载入的
out = new FileWriter(test098.filePath);
}
else
{
//文件是新建的方式
System.out.print("请输入文件保存的绝对路径:");
String path = scan1.next();
test098.filePath = path;
if (! test098.filePath.toLowerCase().endsWith(".txt"))
{
test098.filePath += ".txt";
}
out = new FileWriter(test098.filePath);
}
out.write(test098.message);
out.close();
test098.message = "";
test098.filePath = null;
}
private static void editFile()
{
if (test098.message == "" && test098.filePath == null)
{
System.out.println("请先新建文件或者打开文件");
return;
}
Scanner scan1 = new Scanner(System.in);
System.out.println("请输入要修改的内容(以\"修改的目标文字#修改后的文字\"格式),停止修改请输入\"stop\":");
String inputMsg = "";
while (! inputMsg.equals("stop"))
{
inputMsg = scan1.nextLine();
if (inputMsg != null && inputMsg.length() > 0)
{
String[] editMsg = inputMsg.split("#");
if (editMsg != null && editMsg.length > 1)
{
test098.message = message.replace(editMsg[0], editMsg[1]);
}
}
}
System.out.println("修改后的内容:\r\n" + test098.message);
}
private static void openFile() throws Exception
{
test098.message = "";
Scanner scan1 = new Scanner(System.in);
System.out.println("请输入打开文件的路径:");
test098.filePath = scan1.next();
if (test098.filePath != null && !test098.filePath.endsWith(".txt"))
{
System.out.println("请选择txt文本文件!");
return;
}
FileReader in = new FileReader(test098.filePath);
char[] charArray = new char[1024];
int len = 0;
StringBuffer buffer = new StringBuffer();
while ((len = in.read(charArray)) != -1)
{
buffer.append(charArray);
}
test098.message = buffer.toString();
System.out.println("打开文件内容:\r\n" + test098.message);
in.close();
}
private static void createFile()
{
test098.message = "";
Scanner scan1 = new Scanner(System.in);
System.out.println("请输入内容,停止编写请输入\"stop\":");
StringBuffer buffer = new StringBuffer();
String inputMsg = "";
while (!inputMsg.equals("stop"))
{
if (buffer.length() > 0)
{
buffer.append("\r\n");
}
buffer.append(inputMsg);
inputMsg = scan1.nextLine();
}
test098.message = buffer.toString();
}
}