Java program that edits a text file to display each complete sentence with a period at the end in a separate line
Write a java program that edits a text file to display each complete sentence with a
period at the end in a separate line. Your program should work as follows: Create
a temporary file, copy from the source file to a temporary file and perform the
required operation. Copy the contents of the temporary file back into the source
file. Use a method (or methods) in the class File to remove the temporary file.
You will also want to use the class File for other things in your program. The
temporary file should have a name that is different from all existing files so that
the existing files are not affected (except for the file being edited). Your program
will ask the user for the name of the file to be edited. However, it will not ask the
user for the name of the temporary file, but will instead generate the name within
the program. You can generate the name any way that is clear and efficient. One
possible way to generate the temporary file is to start with an unlikely name, such
as “Temp1”, and to append a digit, such as ‘1’, until a name is found that does
not name an existing file.
Answer:
import java.io.FileInputStream; import java.util.Scanner; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.NoSuchElementException; public class Question { public static void main(String[] args){ try { String word = ""; String tempFile = "TempX"; while (true) { File fileObject = new File(tempFile); if (fileObject.exists()) { tempFile = tempFile + "X"; } // end of if () else { break; } // end of else } // end of while () Scanner keyboard = new Scanner(System.in); System.out.println("Enter filename of file to remove blanks:"); String fileInput = keyboard.nextLine(); Scanner inputStream = new Scanner(new FileInputStream(fileInput)); PrintWriter outputStream = new PrintWriter(new FileOutputStream(tempFile)); String line; while (inputStream.hasNextLine()) { line = inputStream.nextLine(); StringTokenizer st = new StringTokenizer(line, " "); while (st.hasMoreTokens()) { word = st.nextToken(); if (st.hasMoreTokens()) outputStream.print(word + " "); else outputStream.println(word); } // end of while () } inputStream.close(); outputStream.close(); inputStream = new Scanner(new FileInputStream(tempFile)); outputStream = new PrintWriter(new FileOutputStream(fileInput)); while (inputStream.hasNextLine()) { line = inputStream.nextLine(); outputStream.println(line); } inputStream.close(); outputStream.close(); File fileObject = new File(tempFile); fileObject.delete(); } catch (IOException e) { System.out.println("Error reading or writing files."); } } }
Leave a reply