1.Create a class called FileTest. Create a method called createFile that prompts
ID: 3622318 • Letter: 1
Question
1.Create a class called FileTest. Create a method called createFile that prompts the user to enter a filename and then allows the user to type any number of characters and save them to this file. If the file already exists, you should display an error message and not open or overwrite the existing file.2.Create a method that prompts the user to enter a filename and then opens the file and reads the contents. It should then display the contents backward. If the file does not exist, you should display an error message to the user
Explanation / Answer
please rate - thanks
you weren't very specific, especially as to what type of data was in the backwards, so I based it on the first-a bunch of characters
import java.util.*;
import java.io.*;
public class FileTest
{
public static void main(String[] args)throws FileNotFoundException
{createFile();
backwards();
}
public static void createFile() throws FileNotFoundException
{String filename;
String ch;
System.out.print("Enter file name: ");
Scanner in= new Scanner(System.in);
filename=in.nextLine();
File f = new File(filename);
if(f.exists())
System.out.println("program aborted-file already exists");
else
{PrintStream output=new PrintStream(new File(filename));
System.out.print("Enter any number of character ");
ch=in.nextLine();
output.println(ch);
}
}
public static void backwards() throws FileNotFoundException
{String filename;
String ch;
System.out.print("Enter file name: ");
Scanner in= new Scanner(System.in);
filename=in.nextLine();
Scanner input=new Scanner(new File(filename));
ch=input.nextLine();
for(int i=ch.length()-1;i>=0;i--)
System.out.print(ch.charAt(i));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.