该程序的目的是读取文件并将其写入文本文件。
为此我有三个类(class):
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" );
}
}
}
如何编写代码来为用户提供附加数据的选项?
如果有帮助的话,这是类 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;
}
}
我希望我解释清楚
谢谢你 凯尔
最佳答案
如果您希望用户始终追加或始终覆盖一组特定的行,您可以执行以下操作:
System.out.println("Enter false to overwrite data, or true to append data");
userEnter = input.nextLine();
boolean append = Boolean.parseBoolean(userEnter);
如果您将这些行放在循环之外,用户将被询问一次,并且将始终使用相同的值,或者您可以将其放在循环内每次都询问。
WriteFile data = new WriteFile(file_name, append);
关于java - 调用一个类的构造函数来修改它以在另一个类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18975297/