このプログラムの目的は、ファイルをテキスト ファイルに読み書きすることです。
このために、私は3つのクラスを持っています:
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;
}
}
これを明確に説明したことを願っています
ありがとうキール