您好我正在編寫一個程序,使用逐步細化和運行程序來讀取順序文本文件,或者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