该程序的目的是将文件读取和写入文本文件。
为此,我有三个课程:
Class ReadFile //Reads and displays text from the text file
Class WriteFile //Gets input from user and puts it writes it to the text file
Class Application //Holds the Main method for execution.
在WriteFile
类中,我有代码可以将文本追加(添加)文本到文本文件或不追加(删除文本文件中的所有内容,然后将输入写入文本文件,这是由这里的代码完成的
public class WriteFile
{
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path)
{
path = file_path;
}
public WriteFile (String file_path, boolean append_value)
{
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textLine) throws IOException
{
FileWriter write = new FileWriter(path);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}
现在决定是否将数据附加到文本文件的唯一方法是注释掉
append_to_file = append_value;
这当然是用户无法做到的。我想给用户这个选项。
所以我想我可以在类应用程序中添加它,它包含接收输入的代码。
public class Application
{
public static void main(String[] args) throws IOException
{
String file_name = "Q:/test.txt";
try
{
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
for(int i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
}
}
catch (IOException e)
{
System.out.println( e.getMessage());
}
//boolean End = false;
String userEnter;
Scanner input = new Scanner (System.in);
for(int i = 0; i < 10; i++)
{
System.out.println("\n\nenter text to write to file");
userEnter = input.nextLine();
WriteFile data = new WriteFile(file_name, true);
data.writeToFile( userEnter );
System.out.println( "Text File Written To" );
}
}
}
如何编写代码让用户可以选择附加数据?
如果有帮助,这里是 Class ReadFile
public class ReadFile
{
private String path;
public ReadFile (String file_path)
{
path = file_path;
}
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String [numberOfLines];
for(int i = 0; i < numberOfLines; i++)
{
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
我希望我解释清楚
谢谢你凯尔