Checking if a file exists in java - java

So the following program should take in an input and output file as command line arguments.
class FileCopy
{
public static void main(String[] args) throws IOException
{
String infile = null;
String outfile = null;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
if (args.length >= 2) //both files given via command line
{
infile = args[0];
if (fileExists(infile) == false)
{
infile = getInputFile();
}
outfile = args[1];
}
else if (args.length == 1) //input file given via command line
{
infile = args[0];
outfile = getOutputFile(infile);
}
else //no files given on command line
{
infile = getInputFile();
outfile = getOutputFile(infile);
}
//create file objects to use
File in = new File(infile);
File out = new File(outfile);
/*
*rest of code
*/
}
//get the input file from the user if given file does not exist
public static String getInputFile() //throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
boolean haveFile = false;
while(haveFile == false)
{
System.out.println("Enter a valid filename for input:");
System.out.print(">> ");
try
{
fileName = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
haveFile = fileExists(fileName);
}
return fileName;
}
//get the output file and test things
public static String getOutputFile(String infile)
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
File input = new File(infile);
String filename = null;
boolean more = true;
while(more)
{
System.out.println("Enter a valid filename for output:");
System.out.print(">> ");
try
{
filename = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
File output = new File(filename);
if (output.exists())
{
more = false;
}
if (filename == infile)
{
int selection;
String inputString = null;
System.out.println("The output file given matches the input file. Please choose an option:");
System.out.println("1) Enter new filename");
System.out.println("2) Overwrite existing file");
System.out.println("3) Backup existing file");
System.out.print(">> ");
try
{
inputString = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
selection = Integer.valueOf(inputString);
switch (selection)
{
case 1: //new filename
case 2: //overwrite
case 3: //backup
default: System.exit(0);
}
}
}
return null;
}
//check the given file to see if it exists in the current working directory
public static boolean fileExists(String n)
{
return (new File(n)).exists();
}
}

One detail that I believe you have missed:
When your program has only one argument (args.length == 1), i.e. when only the input file is defined, fileExists() is not called at all; infile is set to args[0] with no validation at all. You should probably add a specific check as you have done for the two-argument case.

I've ran into a similar problem too. I was working under eclipse, and had to specify "src/file.txt" with my current directory having a file named "file" in the src directory.
Note: It was not named "file.txt" (this causes the string to be interpreted as "file.txt.txt"!).
Try testing against this program here assuming you have a file named "file" in your "src" directory:
import java.io.File;
public class FileChecker {
public static boolean Exists( String file )
{
System.out.println("File being checked: " + file);
return( (file.length()) > 0 && (new File(file).exists()) );
}
public static void main( String[] args )
{
File dir = new File("src");
System.out.println("List of files in source directory: ");
if( dir.isDirectory()){
File[] filenames = dir.listFiles();
for( Object file : filenames ) {
System.out.println(file.toString());
}
}
else
System.out.println("Directory does not exist.");
if(FileChecker.Exists("src/file.txt"))
System.out.println("File exists");
else
System.out.println("File does not exist");
}
}
It will print out the current files in source directory so you can see whether the file is really there or not, then you can test if it actually exists. Works on my end.

Related

Why is my FileReader not outputting codes from the .txt file?

Sorry If I have any errors because this is my first time asking a question. So basically, my program is converting white_space to underscore and I made it to work. But the problem is, I can't seem to output the inside of my outputfile.txt in the last part of my program.
There should be a premade inputfile.txt for it to work.
Full code:
https://pastebin.com/ecGGd1Z5
Here's the code I'm that's getting problem,
//READING2 No output :(
FileReader yo = new FileReader ("outputfile.txt");
int a;
System.out.println("Outputing from outputfile.txt file ...");
while((a=yo.read())!=-1)
{
System.out.print((char)a);
}
System.out.println("\n");
yo.close();
//
You are not handling the resources correctly. Please find a working example bellow.
It uses "try with resource" so the resource e.g. a FileWriter will be closed correctly:
public class Working {
public static void main(String[] args) throws FileNotFoundException, IOException {
String str;
Scanner scan = new Scanner(System.in);
System.out.println("[Enter source file name: ]");
String input = scan.nextLine();
try (FileReader fread = new FileReader(input)) {
BufferedReader bread = new BufferedReader(fread);
try (FileWriter fwrite = new FileWriter("outputfile.txt")) {
System.out.println(" ");
System.out.println("Creating output file ...");
System.out.println("Output file successly created!");
System.out.println("[Output file name is outputfile.txt]");
System.out.println("=====================");
//READING
FileReader fr = new FileReader(input);
int i;
System.out.println("Outputing from " + input + " file ...");
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
System.out.println("\n");
fr.close();
//
System.out.println("===========");
System.out.println("Starting to convert spaces to underscore ...");
System.out.println("Success!");
System.out.println("===========");
//
while ((str = bread.readLine()) != null) {
str = str.trim();
str = str.replaceAll(" ", "_");
fwrite.write(str);
}
}
//
//READING2 No output :(
try (FileReader yo = new FileReader("outputfile.txt")) {
int a;
System.out.println("Outputing from outputfile.txt file ...");
while ((a = yo.read()) != -1) {
System.out.print((char) a);
}
System.out.println("\n");
}
}
}
}

Scan text file for a string, if found, create new txt file with that string

So what I am trying to do is to scan a txt-file for a String, if that String is found, a new txt-file needs to be created and the String writen into it. The String, the name of the to-be-searched txt-file and the txt-file that will/can be created will be all put in through the command line.
public class FileOperations {
public static void main(String[] args) throws FileNotFoundException {
String searchTerm = args[0];
String fileName1 = args[1];
String fileName2 = args[2];
File file = new File(fileName1);
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
if (searchTerm != null) {
try {
BufferedWriter bw = null;
bw = Files.newBufferedWriter(Paths.get(fileName2), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
bw.write(searchTerm);
bw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
scan.nextLine();
}
scan.close();
}
}
What I tried to do is create a while-loop that scans the original text file for a string, and if that string is found create a txt file and enter that string into it.
What is currently happening is that the original file is scanned (I tested that with System.out.println), but the new file with the string is created no matter if the String is in the original txt-file or not.
Basically, you have just used scanner in wrong way. You need to do that in this way:
String searchTerm = args[0];
String fileName1 = args[1];
String fileName2 = args[2];
File file = new File(fileName1);
Scanner scan = new Scanner(file);
if (searchTerm != null) { // don't even start if searchTerm is null
while (scan.hasNextLine()) {
String scanned = scan.nextLine(); // you need to use scan.nextLine() like this
if (scanned.contains(searchTerm)) { // check if scanned line contains the string you need
try {
BufferedWriter bw = Files.newBufferedWriter(Paths.get(fileName2));
bw.write(searchTerm);
bw.close();
break; // to stop looping when have already found the string
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
scan.close();

Reading and modifying the text from the text file in Java

I am have a project that need to modify some text in the text file.
Like BB,BO,BR,BZ,CL,VE-BR
I need make it become BB,BO,BZ,CL,VE.
and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR.
I have tried to type some code, however the code fail to loop and also,in this case.
IN/CI, GH, KE, NA, NG, SH, ZW /EE, HU, LT, LV, UA,/AR, BB
"AR, BB,BO,BR,BZ,CL, CO, CR, CW, DM, DO,VE-AR-BR-MX"
I want to delete the AR in second row, but it just delete the AR in first row.
I got no idea and seeking for helps.
Please
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class tomy {
static StringBuffer stringBufferOfData = new StringBuffer();
static StringBuffer stringBufferOfData1 = stringBufferOfData;
static String filename = null;
static String input = null;
static String s = "-";
static Scanner sc = new Scanner(s);
public static void main(String[] args) {
boolean fileRead = readFile();
if (fileRead) {
replacement();
writeToFile();
}
System.exit(0);
}
private static boolean readFile() {
System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
filename = "C:\\test.txt";
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine()
&& (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
return true;
} catch (FileNotFoundException ex) {
System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
return false;
} finally {
fileToRead.close();
return true;
}
}
private static void writeToFile() {
try {
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {// if an exception occurs
System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
}
}
private static void replacement() {
System.out.println("Please enter the contents of a line you would like to edit: ");
String lineToEdit = sc.nextLine();
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length() + 2;
String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);
String data = " ";
Scanner sc1 = new Scanner(getdata);
Scanner sc2 = new Scanner(data);
String lineToEdit1 = sc1.nextLine();
String replacementText1 = sc2.nextLine();
int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
boolean test = lineToEdit.contains(getdata);
boolean testh = lineToEdit.contains("-");
System.out.println(startIndex);
if (testh = true) {
stringBufferOfData.replace(startIndex, endIndex, replacementText1);
stringBufferOfData.replace(startIndex1, endIndex1 - 2,
replacementText1);
System.out.println("Here is the new edited text:\n"
+ stringBufferOfData);
} else {
System.out.println("nth" + stringBufferOfData);
System.out.println(getdata);
}
}
}
I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash.
The method reads the file and writes it straight out to a file after editing for the token. This would allow you to process a huge file without worrying about about memory constraints.
You can simply rename the output file after a successful edit. I'll leave it up to you to work that out.
If you feel you really must use string buffers to do in memory management, then grab the logic for the line editing from my method and modify it to work with string buffers.
static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
// the input file
Scanner inputScanner = null;
// output file
FileWriter outputWriter = null;
try
{
// open the input file
inputScanner = new Scanner(new File(inputFilePath));
// open output file
File outputFile = new File(outputPath);
outputFile.createNewFile();
outputWriter = new FileWriter(outputFile);
try
{
for (
String lineToEdit = inputScanner.nextLine();
/*
* NOTE: when this loop attempts to read beyond EOF it will throw the
* java.util.NoSuchElementException exception which is caught in the
* containing try/catch block.
*
* As such there is NO predicate required for this loop.
*/;
lineToEdit = inputScanner.nextLine()
)
// scan all lines from input file
{
System.out.println("START LINE [" + lineToEdit + "]");
// get position of dash in line
int dashInLinePosition = lineToEdit.indexOf('-');
while (dashInLinePosition != -1)
// this line has needs editing
{
// split line on dash
String halfLeft = lineToEdit.substring(0, dashInLinePosition);
String halfRight = lineToEdit.substring(dashInLinePosition + 1);
// get token after dash that is to be removed from whole line
String tokenToRemove = halfRight.substring(0, 2);
// reconstruct line from the 2 halves without the dash
StringBuilder sb = new StringBuilder(halfLeft);
sb.append(halfRight.substring(0));
lineToEdit = sb.toString();
// get position of first token in line
int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
while (tokenInLinePosition != -1)
// do for all tokens in line
{
// split line around token to be removed
String partLeft = lineToEdit.substring(0, tokenInLinePosition);
String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());
if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
// remove prefix comma from right part
{
partRight = partRight.substring(1);
}
// reconstruct line from the left and right parts
sb.setLength(0);
sb = new StringBuilder(partLeft);
sb.append(partRight);
lineToEdit = sb.toString();
// find next token to be removed from line
tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
}
// handle additional dashes in line
dashInLinePosition = lineToEdit.indexOf('-');
}
System.out.println("FINAL LINE [" + lineToEdit + "]");
// write line to output file
outputWriter.write(lineToEdit);
outputWriter.write("\r\n");
}
}
catch (java.util.NoSuchElementException e)
// end of scan
{
}
finally
// housekeeping
{
outputWriter.close();
inputScanner.close();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
inputScanner.close();
e.printStackTrace();
}
}

unable to load file from my computers local directory to java program

i m trying to code for sorting strings,taking input from text file.When i m trying to specify a file for this program is gives me FileNotFoundExcetion
i m unable to understand why?
even i tried to get file path by writing code for that,in the screenShoot u can see that path is correct but the program is still giving me ERROR
here is thet Screenshort
https://app.box.com/s/qytu1d9xlm0vcb6atz42
here is my code
public static void main(String[] args) throws FileNotFoundException, IOException {
ArrayList<String> row1 = new ArrayList<>();
FileWriter writer;
try {
String filename = "1.txt";
String finalfile = "";
String workingDir = System.getProperty("user.dir");
String your_os = System.getProperty("os.name").toLowerCase();
if (your_os.indexOf("win") >= 0) {
finalfile = workingDir + "\\" + filename;
} else if (your_os.indexOf("nix") >= 0 || your_os.indexOf("nux") >= 0) {
finalfile = workingDir + "/" + filename;
} else {
finalfile = workingDir + "{others}" + filename;
}
System.out.println("Final filepath : " + finalfile);
File file = new File(finalfile);
if (file.createNewFile()) {
System.out.println("Done");
} else {
System.out.println("File already exists!");
}
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(new FileReader("finalfile"))) {
String s;
while ((s = reader.readLine()) != null) {
row1.add(s);
}
Collections.sort(row1);
writer = new FileWriter("output.txt");
for (String s1 : row1) {
writer.write(s1 + "\n");
}
reader.close();
writer.close();
} catch (Exception e) {
System.out.print("Error : " + e);
}
}
In
BufferedReader reader = new BufferedReader(new FileReader("finalfile")))
the parameter to the FileReader constructor is hard coded as "finalfile" - you need to use the variable instead:
BufferedReader reader = new BufferedReader(new FileReader(finalfile)))
^^^^^^^^^^^
You also need to move String finalfile = ""; before the first try block, otherwise it is out of scope when you are creating the FileReader.
Also, there is no need to query the operating system and manually set the directory path separator. If you really need to, use File.separator. Otherwise, simply use the forward slash - this is working cross-platform.
It is good to see that you are using try-with-resources - however, you should do it consequently; simply create all required resources in the try statement, and then there is no need to explicitly close them:
try (BufferedReader reader = new BufferedReader(new FileReader(finalfile));
FileWriter writer = new FileWriter("output.txt")) {
...
// reader and writer will be auto-closed
} catch (IOException e) {
System.out.print("Error : " + e);
}

Error: java.util.NoSuchElementException - Scanner not behaving as desired

Scanner returning NoSuch Element Exception error. Could you explain why is this happening.
The Scanner now passes and runs fine but it didn't take the nextLine input from the second Scanner call. This may be a little tweak but could someone point out what the mistake is.
public class JavaHW1_1 {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) throws IOException {
String pattern ;
String fileName = null;
// Method to manage user inputs
fileName = userInputFileName(userInput);
pattern = userInputPattern(userInput);
// To find the pattern in the file
// findPattern();
}
private static String userInputPattern(Scanner userInput) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
while(userInput.hasNextLine()){
pattern = userInput.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
}
userInput.close();
return pattern;
}
private static String userInputFileName(Scanner userInput) throws IOException {
String path = "./src";
String files, fileName;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
System.out.println("Please input the desired file name:\n");
System.out.println("Some suggestions:\n");
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".txt"))
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
int userAttempt = 0;
do{
fileName = userInput.nextLine();
if(fileName.toLowerCase().endsWith(".txt")){
System.out.println("The file name entered is in correct format");
File file = new File("./src",fileName);
try {
file.createNewFile();
System.out.println("File is created. Please enter text to be written in the file. End the content with \"eof\"");
InputOutput(file.getName());
} catch (IOException e) {
e.printStackTrace();
}
userAttempt = 10;
}
else
{System.out.println("Please enter correct format file with .txt extension");
userAttempt++;}
}while (userAttempt <10);
return fileName;
}
private static void InputOutput(String fName) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("./src/" + fName));
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("aaa"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
private static void findPattern() {
// TODO Auto-generated method stub
}
}
Based in this SO, you might be closing the Scanner and creating a new one to read from the System.in and it makes sense by looking at your code.
So my suggestion for you code is to receive the Scanner by parameter, something like this:
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
String pattern = userInputPattern(scan);
String test = readSomethingElse(scan);
}
private static String readSomethingElse(Scanner scan) {
System.out.println(". Read something else");
return scan.nextLine();
}
private static String userInputPattern(Scanner scan) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
pattern = scan.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
return pattern;
}
It could happen if you pass EOF straight into the standard input. For example (in windows):
java com.myprog.MainClass
^Z
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
....
The ^Z above represents a Ctrl-Z on windows command prompt which is an EOF signal
You need to consider your requirement and process / display error if user is provided a EOF without any prior data

Categories

Resources