您好我正在编写一个程序,使用逐步细化和运行程序来读取顺序文本文件,或者1)插入2)修改或3)删除用户输入的条目。目前我的问题是我需要输入一个存在的字符串(如果它没有退出),然后将它与“输出”(或修改过的)字符串进行比较以修改它。阅读文本文件的每一行并将其与用户输入进行比较
import java.io.*;
import java.nio.file.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.Scanner;
public class master2{
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1.insertion into file 2.modify into file 3.delete in file");
int choice=sc.nextInt();
try
{
File newTextFile = new File("masterfile.txt");
File temp = File.createTempFile("duplicateMaster", ".txt", newTextFile.getParentFile());
String charset = "UTF-8";
if(choice==1)
{
System.out.println("Enter String to insert");
String str = sc.next();
FileWriter fw = new FileWriter("masterfile.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fw);
Scanner fileSC = new Scanner(newTextFile);
int count = 0;
while(fileSC.hasNextLine())
{
String line = fileSC.nextLine();
System.out.print("Line " + count + " ");
count++;
if (line.compareTo(str)==0)
{
System.out.println("Data already exists!");
System.exit(0);
}
}
fw.append("\n" + str);
System.out.println("Entry added!");
fw.close();
fileSC.close();
System.exit(0);
}
if(choice==2){
Path path = Paths.get("masterfile.txt");
String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
System.out.println("Enter String you want to modify which is present in text file");
String input = sc.next();
System.out.println("Enter new modified string");
String output = sc.next();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(newTextFile), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
Scanner fileSC = new Scanner(newTextFile);
int count = 0;
while(fileSC.hasNextLine())
{
String line = fileSC.nextLine();
System.out.print("Line " + count + " ");
count++;
if (line.contains(input))
{
content = line.replace(input, output);
writer.write(content);
}
}
newTextFile.delete();
temp.renameTo(newTextFile);
System.out.print("Modified");
reader.close();
writer.close();
}
if(choice==3)
{
String delete = "foo";
System.out.println("Enter string to delete");
delete = sc.nextLine();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(newTextFile), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
temp.renameTo(newTextFile);
temp.delete();
}
}
}catch (Exception e)
{
System.out.println(e);
}
}
}
我最近为'hasNextLine()'添加了while循环,所以我意识到这可能是不正确的。 – MrCptObvious 2015-04-03 17:46:18
您在这里缺少了很多代码,因为它在if(block == 2)块的末尾被截断,并且代码格式化可以使用很多工作。如果您使用的是IDE,则可以为您进行格式设置。 – lealand 2015-04-03 20:02:32
我只是在放snipplets,因为我不想看起来像我要求它为我做。我更新了整个代码。 – MrCptObvious 2015-04-03 20:41:11