import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static Scanner userScanner = new Scanner(System.in);
public static void main(String[] args) {
Scanner fileScanner = openInputFile();
if (fileScanner == null)
return;
fileScanner.nextLine();
while(fileScanner.hasNextLine()){
//handle input
}
fileScanner.close();
}
public static Scanner openInputFile() {
String filename;
Scanner scanner = null;
System.out.print("Enter the input filename: ");
filename = userScanner.nextLine();
File file = new File(filename);
try {
scanner = new Scanner(file);
} // end try
catch (FileNotFoundException fe) {
System.out.println("Can't open input file\n");
return null; // array of 0 elements
} // end catch
return scanner;
} // end openInputFile
}
I'm trying to open an input file using the following method but it prints "Can't open input file" every time. I double checked the spelling, the file is in the same directory. Am I doing anything wrong?
Related
I am making a program which will create files and delete files etc. but the program can only create one file and after doing that it gets terminated, so I want to use String as name of create_file class object name so I can increment the numbers(String used as name of the object) so my question is, how can I use String as object name of a class constructor?
below is the source code of the program-
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Create_File {
public static void main(String[] args) throws IOException {
try {
Selecter.select();
}
catch(Exception e) {
e.printStackTrace();
}
}
static void create() throws IOException {
String name;
System.out.println("Enter a name for your file");
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));){
name = reader.readLine();
//this block is used as try with resource statement used to overcome scanner resource leak
}
try{
//file is created with the name that user gives
File obj = new File("D:\\txtfiles\\"+name+".txt");
if(obj.createNewFile()) {
System.out.println("file successfully created with the name "+obj.getName());
}
else{
System.out.println("The file already exists");
}
}
catch(IOException e){
//here exception during file creation is caught
System.out.println("An error occurred.");
e.printStackTrace();
}
// info(name);
name = null;
// Selecter.select();
}
static void info(String name) throws IOException {
File obj = new File("D:\\txtfiles\\"+name+".txt");
String data = null;
Scanner scan = new Scanner(obj);
if(obj.exists()) {
//file properties are printed out for both newly created file and the existing file
System.out.println("File properties");
System.out.println("Name of the file = "+obj.getName());
System.out.println("Path of file = "+obj.getAbsolutePath());
System.out.println("Size of file in Kb= "+obj.length()/1024); // obj.lengeth is divided by 1024 to get the file size in Kb
System.out.println("Readable = "+obj.canRead());
System.out.println("Writable = "+obj.canWrite());
}
else {System.out.println("the file does not exist");
//this block is used as try with resource statement used to overcome scanner resource leak
while(scan.hasNextLine()) {
data = scan.nextLine();
System.out.println(data);
}
}
// Selecter.select();
}
static void delete(String name) throws IOException {
try{
File obj = new File("D:\\txtfiles\\"+name+".txt");
obj.delete();
if(obj.exists()==false) {
System.out.println("file deleted successfully");
}
else {
System.out.println("file does not exist");
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
below is the source code of Selecter class-
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Selecter {
static void select() throws IOException {
String num=null;
Create_File create =new Create_File();
System.out.println("Select Action");
System.out.println("1. Create new text file");
System.out.println("2. Delete an existing file");
System.out.println("3. Find info of a file");
System.out.println("4. Print the contents of a file");
System.out.println("5. EXIT");
System.out.println("Your choice = ");
try
(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));){
int choice = Integer.parseInt(num= reader.readLine());
if(choice==1) {
create.create();
}
else if(choice == 2){
System.out.println("enter file name to delete");
String name=reader.readLine();
create.delete(name);
}
else if(choice == 3) {
System.out.println("enter file name to find its info");
String name= reader.readLine();
create.info(name);
}
else if(choice ==4) {
Buffer contents = new Buffer();
Buffer.main(null);
}
else if(choice == 5) {
System.exit(0);
}
}
// select();
}
}
or is there an alternative solution for this problem I want the program to keep running till the user wants to exit.
I need to input a line of text into the code and have it print that text to the file in all upper came, all lower case, and reverse. I know how to do this with string, but cannot figure out how to get it to print to the file this way. I do not need help with getting the text to print in the output but getting it to print all these ways to the actual PrintToFile.txt without actually inputting it all those different ways.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PrintToFile { //open class
private static Formatter output;
public static void main (String args[]) throws IOException { //open main
openFile();
addRecords();
closeFile();
BufferedReader printFile = new BufferedReader(new FileReader("YoastReginaITM251Project9.txt"));
for (String line; (line = printFile.readLine()) != null;) { //open for
System.out.println("Text: " + line);
System.out.println("Text in Upper Case: " + line.toUpperCase());
System.out.println("Text in Lower Case: " + line.toLowerCase());
System.out.println("Text in Reverse Case: " + line);
} //close for
} //close main
public static void openFile() { //open openFile
try { //open try
output = new Formatter("PrintToFile.txt"); //open file
} //close try
catch (SecurityException securityException) { //open catch
System.err.println("Write permission denied. Terminating.");
System.exit(1);
} //close catch
catch (FileNotFoundException fileNotFoundException) { //open catch
System.err.println("Error opening file. Terminating.");
System.exit(1);
} //close catch
} //close openFile
public static void addRecords() { //open addRecords
try { //open try
output.format("%s", input.nextLine());
} //close try
catch (FormatterClosedException formatterClosedException) { //open catch
System.err.println("Error writing to file. Terminating.");
} //close catch
catch (NoSuchElementException elementExpcetion) { //open catch
System.err.println("Invalid input. Please try again.");
input.nextLine();
} //close catch
} //close AddRecords
public static void closeFile() { //open closeFile
if (output != null)
output.close();
} //close closeFile
} //close class
String input = "MagicString";
String upperCase = input.toUpperCase();
String lowerCase = input.toLowerCase();
StringBuilder sb = new StringBuilder();
sb.append(input);
String reversedString = sb.reverse().toString();
You can use the StringBuilder class (https://docs.oracle.com/javase/tutorial/java/data/buffers.html) to create new strings as you like, then print those to file.
The simple way is:
Read from a file into a string.
Apply toUpperCase() and store it into another string.
Apply toLowerCase() and store it into another string.
Apply reverse()[own created method] and store it into another string.
Then write all these strings into the destination file.
Here is the code by which you can perform the required operation.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileRW {
public static void main(String[] args) throws FileNotFoundException, IOException {
String filename="filename.txt";
String upper,lower,reverse,line;
upper=null;
lower=null;
reverse=null;
line=null;
FileReader fileReader=new FileReader(filename);
BufferedReader bufferedReader=new BufferedReader(fileReader);
while((line=bufferedReader.readLine())!=null)
{
upper=line.toUpperCase();
lower=line.toLowerCase();
reverse=reverse(line);
writeToFile(upper,lower,reverse);
}
}
static String reverse(String test)
{ String returnString="";
int len=test.length();
for(int i=len-1;i>=0;i--)
{
returnString+=test.charAt(i);
}
return returnString;
}
static void writeToFile(String line1,String line2,String line3) throws IOException
{
String filename="content.txt";
File file =new File(filename);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(line1);
bufferWritter.write(line3);
bufferWritter.write(line2);
bufferWritter.close();
System.out.println("Done");
}
}
Maybe you could use the Scanner and FileWriter classes as well. You can try something like this if it works for your purposes:
import java.io.*;
import java.util.*;
public class Solution{
/*
* Print a string to the output file
*/
private void print(String s, FileWriter o) {
try {
o.write(s + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* Convert the strings to uppercase,
* lowercase and reverse.
*/
private void solver(Scanner sc, FileWriter o){
while(sc.hasNextLine()) {
String s = sc.nextLine();
print(s.toUpperCase(), o);
print(s.toLowerCase(), o);
print(new StringBuilder(s).reverse().toString(), o);
}
}
/*
* Main method
*/
public static void main(String args[]){
File inFile = new File("input.txt");
File outFile = new File("output.txt");
try{
Scanner sc = new Scanner(inFile);
FileWriter o = new FileWriter(outFile);
Solution s = new Solution();
s.solver(sc, o);
sc.close();
o.close();
} catch(Exception e){
System.out.println(e);
}
}
}
How would I go about making my program terminate once it reaches a specific word from a file. So far, I have it printing out all the words from the file which I want. "input" contains the words "one two three four galumph" just like that.
import java.util.Scanner;
import java.io.*;
class EchoWords {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("input"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (sc2.hasNext()) {
String s = s2.next();
System.out.println(s);
}
}
}
}
Can someone please help me determine what I am doing wrong with my code. I am getting a stackoverflow error. At the end of my code I am using recursion and I don't have a base case to stop the program. It keeps looping and displaying my text file until I get a stackoverflow error.
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Joseph\\Documents\\School Files - NHCC\\CSci 2002\\FinalQuestionBank_JosephKraemer.txt"); //file location
try
{
Scanner scan = new Scanner(textFile); //Scanner to import file
while(scan.hasNextLine()) //Iterator - while file has next line
{
String qBank = scan.nextLine(); //Iterator next line
String[] tempArray = qBank.split("::"); //split data via double colon
System.out.println(qBank); //print data line
}
scan.close(); //close scanner
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return readFinalQuestionBank(); //use of Recursion
}//end method readFinalQuestionBank
}//end class Reader
if your main objective is to read the whole input file by implementing recursivity take a look at the following example, it replaces the while statement with a recursive method call.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Diego\\Documents\\sandbox\\input.txt");
String output = "";
try
{
Scanner scan = new Scanner(textFile);
output = readLineRecursively(scan);
scan.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return output;
}
private static String readLineRecursively(Scanner scan){
if(!scan.hasNextLine()){
return "";
}
String qBank = scan.nextLine();
return qBank + "\n" + readLineRecursively(scan);
}
public static void main(String[] args){
try {
System.out.println(readFinalQuestionBank());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have written the following very simple Java program to ask user enter a file name, then it will report the number of lines of this file to the standard output:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
It is working.I would be really thankful if experts could help me
see if there is anything that can be improved in this code fragment,
If the file is not found, the exception is caught in the outermost catch statement and print out the stack trace. However, I think it is not very user-friendly, is there a way if the file does not exist, then the whole process restarts from beginning?
Thanks in advance.
Get some Structure in your code:
public static void main(String[] args)
{
string output;
string fname = readFileName();
if (fileValid(fname)) //Ensure FileExists
{
int lineCount = scaneFile(fname);
output = "some output text including line numbers"
}
else
{
output = "File Not Valid..."
}
//showOutput...
}
Obvious change is to make a method countLines(String filename) that contains most of the code currently in main(). Obviously main() will call countLines().
Prompting for a file could live in main() or another method.
To restart on error you need a loop like:
filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
try {
int numLines = countLines(filename);
println("num lines in " + filename + "=" +numLines);
}
catch(Exception ex) { // or just specific excpetions
ex.printStackTrace();
}
}
Unless you want to make a GUI. I suggest you receive the path to the file as a command line parameter.
If file doesn't exist print a message and exit. That's all.
The command line will give the user the option to move up with the up-key, edit the name and run again.
This class is named LineCounter and is the "business logic"
package countlines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
private int lineCount = 0;
public LineCounter(File file) throws IOException{
BufferedReader inFile = new BufferedReader(new FileReader(file));
while(inFile.readLine() != null) {
lineCount++;
}
inFile.close();
}
public int getLineCount() {
return lineCount;
}
}
This class is the "presentation logic"
package countlines;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main (String[] args){
if (args.length != 1){
System.out.println("Usage: java countlines/Main filePath");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()){
System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
System.exit(2);
}
if (f.isDirectory()){
System.out.println(f.getAbsolutePath()+" is a directory");
System.exit(2);
}
LineCounter c;
try {
c = new LineCounter(f);
System.out.println(c.getLineCount());
} catch (IOException e) {
System.out.println("Error reading file " + f.getAbsolutePath());
}
}
}