Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

this is in java 1. Selects a text file from your computer using a Java Swing JFi

ID: 2246565 • Letter: T

Question

this is in java

1. Selects a text file from your computer using a Java Swing JFileChooser or a JavaFX FileChooser, which starts out showing the files in the same directory from which the program was executed.

2.Reads the selected text file. The text file for my test will consist of a number of rows, each row containing one or more strings of characters, separated by spaces. The strings themselves will only contain printable, non-space characters.

3. Writes the final string of each input line to a separate line on the output file. The output text file will be in the same directory as the input text file, where the naming convention is as follows: If the input file is abc.txt, the output file is abc_out.txt.

Explanation / Answer

1. This is for file selection using JavaFxFilechoser

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select text file");
fileChooser.setInitialDirectory(new File("X:\testdir\two"));
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"));
File selectedFile = fileChooser.showOpenDialog(null);
if (selectedFile != null) {
actionStatus.setText("PDF file selected [" + selectedFile.size() + "]: " + selectedFile.getName() + "..");
}
else {
actionStatus.setText("PDF file selection cancelled.");
}

2. this is for reading the text file line by line:

try {
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
e.printStackTrace();
}

where we get the file object f from previous step.

3. To get last string from each line :

String[] words=readLine.split("\s");
String last_word = words.at(words.length()-1);

now to write in file:
BufferedWriter writer = new BufferedWriter(new FileWriter(
filename));

and to write you can use:

writer.write(last_word);
writer.newLine();