Results 1 to 17 of 17
  1. #1
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    95
    Rep Power
    0

    Default My package hierarchy looks right, I'm having syntax issues with File IO.

    Hi. I'm just starting the Java File IO chapter, and am getting some errors despite doing exactly what they say in the book.

    Here's my packaging:
    My package hierarchy looks right, I'm having syntax issues with File IO.-fileiopaths.png

    And here's my code:
    FileIO.java
    Java Code:
    package samsExperiments;
    import java.io.*;
    import java.nio.file.*;
    
    public class FileIO {
    	
    	//get a path object for the file
    	Path myFilePath = Path.get(myFile.txt);
    	File myFileFile = myFilePath.toFile();
    	
    	//write data to the file
    	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFileFile)));//open an output stream
    	
    	out.@println("AVGN2\tSecurity Breach\t55000");//write data to the stream
    	out.close();
    	
    	//read data from the file
    	BufferedReader in = new BufferedReader(new FileReader(myFileFile));//open an input stream
    	
    	String line = in.readLine();
    	System.out.@println(line);
    	in.close();
    }
    Line 9 error: "myFile cannot be resolved to a variable". If I put quotes around myFile.txt, I get the error, "myFile cannot be resolved to a variable".

    Line 15 error: "Syntax error on token ";", @ expected".

    Line 16 error: "Syntax error, insert ")" to complete MethodDeclaration".

    Line 21 error: "Syntax error on token ";", @ expected".

    Line 22 error: "Syntax error, insert ")" to complete MethodDeclaration".


    Are those errors normal? Also, does anyone know whether this is Java version 8 or 9?

    Thanks.
    Last edited by Norm; 07-04-2019 at 11:01 PM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,995
    Rep Power
    32

    Default Re: My package hiarchy looks right, I'm having syntax issues with File IO.

    The method declaration is missing. Much of the code must be inside of a method.
    Java Code:
     Path myFilePath = Path.get(myFile.txt);
    Where is the get method of the Path interface defined? I can not find it.
    Last edited by Norm; 07-04-2019 at 12:34 PM.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: My package hiarchy looks right, I'm having syntax issues with File IO.

    Quote Originally Posted by Norm View Post
    The method declaration is missing. Much of the code must be inside of a method.
    Java Code:
     Path myFilePath = Path.get(myFile.txt);
    Where is the get method of the Path interface defined? I can not find it.
    It's java.nio.file.Paths, with an 's'. It was introduced in Java 1.7. The rest of the code dates back to java 1.1 :)
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  4. #4
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    95
    Rep Power
    0

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    Mostly fixed, except for a couple annoying errors:

    Java Code:
    package samsExperiments;
    import java.io.*;
    import java.nio.file.*;
    
    public class FileIO {
    	
    	//Create a directory if it doesn't already exist
    	String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    	Path dirPath = Paths.get(dirString);
    	if(Files.notExists(dirPath)) {
    		Files.createDirectories(dirPath);
    	}
    	
    	/*public String createDirectory() {
    		String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    		Path dirPath = Paths.get(dirString);
    		if(Files.notExists(dirPath)) {
    			Files.createDirectories(dirPath);
    		}
    		return dirString;
    	}*/
    	
    	//Create a file if it doesn't already exist
    	String fileString = "myFile.txt";
    	Path filePath = Paths.get(dirString,fileString);
    	if(Files.notExists(filePath)) {
    		Files.createFile(filePath);
    	}
    		
    	/*public String createFile() {
    		String fileString = "myFile.txt";
    		String dirString = createDirectory();
    		Path filePath = Paths.get(dirString,fileString);
    		if(Files.notExists(filePath)) {
    			Files.createFile(filePath);
    		}
    		return fileString;
    	}*/
    	
    	//get a path object for the file
    	Path myFilePath = Paths.get("myFile.txt");
    	File myFileFile = myFilePath.toFile();
    	
    	//write data to the file
    	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFileFile)));//open an output stream
    	
    	out.println("AVGN2\tSecurity Breach\t55000");//write data to the stream
    	out.close();
    	
    	//read data from the file
    	BufferedReader in = new BufferedReader(new FileReader(myFileFile));//open an input stream
    	
    	String line = in.readLine();
    	System.out.println(line);
    	in.close();
    	
    	//Display all of the files in a directory (page 463)
    	if(Files.exists(dirPath) && Files.isDirectory(dirPath)) {
    		System.out.println("Directory: " + dirPath.toAbsolutePath());
    		System.out.println("Files:" );
    		DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath);
    		for(Path p:dirStream) {
    			if(Files.isRegularFile(p)) {
    				System.out.println("  " + p.getFileName());
    			}
    		}
    	}//end of if files exists if statement
    
    }//end of FileIO class
    line 9: "Syntax error on token ";", { expected after this token".

    line 69: "Syntax error, insert "}" to complete ClassBody".


    I don't know what it wants from me. I've verified that I have the correct number of curly braces. Am I missing something?

  5. #5
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    You have all your code in the class scope, and you should make a method to put it in.

    So NOT like this:
    Java Code:
    public class FileIO {
    ** your code here**
    }
    but like this:

    Java Code:
    public class FileIO {
       public void myMethod() {
          ** your code here**
       }
    }
    - If the method returns something, replace void with whatever the method returns.
    - If this method is used without and instance of FileIO, make it static:
    Java Code:
    public class FileIO {
       public static void myMethod() {
          **your code here** 
       }
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  6. #6
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    95
    Rep Power
    0

    Default Re: My package hiarchy looks right, I'm having syntax issues with File IO.

    Quote Originally Posted by SurfMan View Post
    It's java.nio.file.Paths, with an 's'. It was introduced in Java 1.7. The rest of the code dates back to java 1.1 :)
    So then this code would be for java versions 6 and earlier:
    Java Code:
    //Java program to demonstrate FileNotFoundException 
    import java.io.File; 
    import java.io.FileNotFoundException; 
    import java.io.FileReader; 
     class File_notFound_Demo { 
      
        public static void main(String args[])  { 
            try { 
      
                // Following file does not exist 
                File file = new File("E://file.txt"); 
      
                FileReader fr = new FileReader(file); 
            } catch (FileNotFoundException e) { 
               System.out.println("File does not exist"); 
            } 
        } 
    }
    Anyway, with that trivial matter out of the way, my FileIO class is now making me use try catch statements. In fact, it won't even allow me to compile the code until I do, so here's the deal.
    My book gave me a nice example of how to make a function that reads a file with exception handling (lines 6 to 22) in the following updated code:
    Java Code:
    package samsExperiments;
    import java.io.*;
    import java.nio.file.*;
    
    public class FileIO {
    	public void readFileWithIOE() {
    		Path theFilePath = Paths.get(createFile());
    		if(Files.exists(theFilePath)){
    			File theFile = theFilePath.toFile();
    			try(BufferedReader in = new BufferedReader(new FileReader(theFile))){
    				String line = in.readLine();
    				while(line != null) {
    					System.out.println(line);
    					line = in.readLine();
    				}
    			}catch(IOException e) {
    				System.out.println(e);
    			}
    		}else {
    			System.out.println(theFilePath.toAbsolutePath() + " doesn't exist");
    		}
    	}
    	
    	//Create a directory if it doesn't already exist
    	/*String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    	Path dirPath = Paths.get(dirString);
    	if(Files.notExists(dirPath)) {
    		Files.createDirectories(dirPath);
    	}*/
    	
    	public String createDirectory() {
    		String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    		Path dirPath = Paths.get(dirString);
    		if(Files.notExists(dirPath)) {
    			Files.createDirectories(dirPath);
    			//try catch constructor needed here
    			try()
    		}
    		return dirString;
    	}
    	
    	//Create a file if it doesn't already exist
    	/*String fileString = "myFile.txt";
    	Path filePath = Paths.get(dirString,fileString);
    	if(Files.notExists(filePath)) {
    		Files.createFile(filePath);
    	}*/
    		
    	public String createFile() {
    		String fileString = "myFile.txt";
    		String dirString = createDirectory();
    		Path filePath = Paths.get(dirString,fileString);
    		if(Files.notExists(filePath)) {
    			Files.createFile(filePath);
    		}
    		return fileString;
    	}
    	
    	public Object getPathWriteRead() {
    		//get a path object for the file
    		Path myFilePath = Paths.get(createFile());//Path myFilePath = Paths.get("myFile.txt");
    		File myFileFile = myFilePath.toFile();
    		
    		//write data to the file
    		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFileFile)));//open an output stream
    		
    		out.println("AVGN2\tSecurity Breach\t55000");//write data to the stream
    		out.close();
    		
    		//read data from the file
    		BufferedReader in = new BufferedReader(new FileReader(myFileFile));//open an input stream
    		
    		String line = in.readLine();
    		System.out.println(line);
    		in.close();
    	}
    	
    	public void showAllFilesInDirectory() {
    		//Display all of the files in a directory (page 463)
    		if(Files.exists(dirPath) && Files.isDirectory(dirPath)) {
    			System.out.println("Directory: " + dirPath.toAbsolutePath());
    			System.out.println("Files:" );
    			DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath);
    			for(Path p:dirStream) {
    				if(Files.isRegularFile(p)) {
    					System.out.println("  " + p.getFileName());
    				}
    			}
    		}//end of if files exists if statement
    	}
    	
    
    }//end of FileIO class
    Seeing how the buffered reader parameters supplied the try statement on line 10, I have no idea where to even begin with the try catch processes for createDirectory and createFile functions, because they aren't reading or writing to a file; rather, they're creating a path and a file. So, to get rid of the "Unhandled exception type IOException" error on lines 35 and 54, what is needed for the try catch structure in those parts of the code?

  7. #7
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    The method Files.createDirectories() throwsn IOException when things go wrong, like you don't have permissions, duplicate names etc. You *MUST* do something with it. It's called a "checked exception", which means you can't ignore it. There are two ways to handle this:
    1) Surround that line with a try and catch block like this to handle it properly like this:
    Java Code:
    try {
       Files.createDirectories(...);
    } 
    catch( IOException e) {
     //decide what to do with the exception here.
    }
    2) You can tell the method signature to throw the exception to the code that called it, but then you'd have to handle it there similiar in 1)
    Java Code:
    public String createDirectory() throws IOException {
       Files.createDirectories(...);
    }
    This will not complain anymore, but the exception is now the responsibility of the caller.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  8. #8
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    95
    Rep Power
    0

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    I'm having some issues with the existence of .txt files in my directory.

    FileIO.java
    Java Code:
    package samsExperiments;
    import java.io.*;
    import java.nio.file.*;
    import java.util.Scanner;
    
    public class FileIO {
    	
    	public String createFile() throws IOException{		
    		String fileString = "myTextFile.txt";
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileString);
    		if(Files.notExists(myFilePath)) {
    			Files.createFile(myFilePath);//create a file if it doesn't already exist
    		}
    		return fileString;
    	}
    	
    	public String createDirectory() {
    		String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    		Path dirPath = Paths.get(dirString);
    		if(Files.notExists(dirPath)) {
    			try {
    				Files.createDirectories(dirPath);
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}
    		return dirString;
    	}
    	
    	//Note that this writeToFile() function as it is, always overwrites the first lines of the text file
    	public void writeToFile() throws IOException{
    		String fileName = createFile();
    		Path myFilePath = Paths.get(fileName);//Path myFilePath = Paths.get("myFile.txt");
    		File myFile = myFilePath.toFile();
    		//write data to the file
    		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFile)));//open an output stream
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y")) {
    			Scanner input = new Scanner(System.in);
    			System.out.println("Enter a sentence of text to add a line to the " + myFile + " file:");
    			String text = input.nextLine();
    			out.println(text);
    			System.out.print("Do you want to add another line?(y/n)  ");
    			choice = input.nextLine();
    			System.out.println();
    		}
    		out.close();
    	}		
    	
    	public void readFile() throws IOException {
    		String fileName = createFile();
    		System.out.println("The retrieved fileName string is: " + fileName);
    		Path myFilePath = Paths.get(fileName);
    		System.out.println("The file path is: " + myFilePath + "\n");
    		if(Files.exists(myFilePath)){
    			File theFile = myFilePath.toFile();
    			try(BufferedReader in = new BufferedReader(new FileReader(theFile))){//open an input stream
    				String line = in.readLine();
    				while(line != null) {
    					System.out.println(line);
    					line = in.readLine();
    				}
    				in.close();
    				System.out.println();
    			}catch(IOException e) {
    				System.out.println(e);
    			}
    		}else {
    			System.out.println(myFilePath.toAbsolutePath() + " doesn't exist");
    		}
    	}
    	
    	public void deleteFile() throws IOException{
    		String fileName = createFile();
    		Path myFilePath = Paths.get(fileName);
    		if(Files.exists(myFilePath)) {
    			Files.deleteIfExists(myFilePath);
    			System.out.println(fileName + " should now be gone from directory.\n");
    		}
    		else if(Files.notExists(myFilePath)) {
    			System.out.println("File not found. Nothing to delete.\n");
    		}		
    	}	
    	
    	public void showAllFilesInDirectory() {
    		//Display all of the files in a directory (page 463)
    		String dirString = createDirectory();
    		Path dirPath = Paths.get(dirString);
    		if(Files.exists(dirPath) && Files.isDirectory(dirPath)) {
    			try {
    				System.out.println("Directory: " + dirPath.toAbsolutePath());
    				System.out.println("Files:" );
    				DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath);
    				for(Path p:dirStream) {
    					if(Files.isRegularFile(p)) {
    						System.out.println("  " + p.getFileName());
    					}
    				}
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}//end of if files exists if statement
    	}
    
    }//end of FileIO class
    samsExperimentsMain.java
    Java Code:
    package samsExperiments;
    
    import java.util.Scanner;
    import java.io.IOException;
    
    public class SamsExperimentsMain {
    	
    	public static void main(String[] args){
    		
    		// C:\murach\java_eclipse\SamsProjects\RandomExperiments\src\samsExperiments
    		
    		FileIO fio = new FileIO();
    		try {
    			
    			fio.createFile();			
    			
    			fio.createDirectory();			
    			
    			fio.writeToFile();
    			
    			fio.readFile();
    			
    			fio.deleteFile();
    			
    			fio.showAllFilesInDirectory();
    			
    		} catch (IOException e) {
    			e.printStackTrace();
    			System.out.println(e);
    		}		
    		
    	}//end of main method	
    }//end of class

    I tried changing up the createFile() to take a Path object from the createDirectory() by changing its function's return type to Path instead of String, but that causes an error on line 11 that says, "The method get(String, String...) in the type Paths is not applicable for the arguments (Path, String)".

    So I guess that won't make any difference as to why the the delete function doesn't seem to be doing its job, because the myFile.txt and myTextFile.txt file names are still in the output of the showAllFilesInDirectory() function:


    Output sample:
    Enter a sentence of text to add a line to the myTextFile.txt file:
    im a sentence
    Do you want to add another line?(y/n) y

    Enter a sentence of text to add a line to the myTextFile.txt file:
    im another sentence
    Do you want to add another line?(y/n) n

    The retrieved fileName string is: myTextFile.txt
    The file path is: myTextFile.txt

    im a sentence
    im another sentence

    myTextFile.txt should now be gone from directory.

    Directory: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\src\samsExperiments
    Files:
    BinarySearch.java
    Box.java
    FileIO.java
    FixString.java
    GenericsSuite.java
    InnerClassTest.java
    Maps.java
    myFile.txt
    myTextFile.txt
    OrderedPair.java
    Queue.java
    RandomClass.java
    SamsArrays.java
    SamsDataStructures.java
    SamsExperimentsMain.java
    SamsThreads.java
    Shapes.java
    temporaryDump.java
    TimeZones.java
    WordAppearanceCounterApp.java
    WorkingTestedCodeRepository.java

    In addition, neither of those text files are not showing up in my Eclipse IDE package:
    My package hierarchy looks right, I'm having syntax issues with File IO.-notextfilesvisible.png

    Any ideas on why I can only see them in the output of the showAllFilesInDirectory() function call, but not in my project package hierarchy?
    Any ideas on why the deleteFile() function doesn't seem to be doing its job?

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,995
    Rep Power
    32

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    Add some more debug print statements to show where the files and folders that are being worked with are located.
    Also print out the boolean results returned by the methods.
    If you don't understand my response, don't ignore it, ask a question.

  10. #10
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    95
    Rep Power
    0

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    Quote Originally Posted by Norm View Post
    Add some more debug print statements to show where the files and folders that are being worked with are located.
    Also print out the boolean results returned by the methods.
    Here's the code with some debugging statements:
    Java Code:
    package samsExperiments;
    import java.io.*;
    import java.nio.file.*;
    import java.util.Scanner;
    
    public class FileIO {
    	
    	public String createFile() throws IOException{		
    		String fileString = "myTextFile.txt";
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileString);
    		if(Files.notExists(myFilePath)) {
    			Files.createFile(myFilePath);//create a file if it doesn't already exist
    		}
    		return fileString;
    	}
    	
    	public String createDirectory() {
    		String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    		Path dirPath = Paths.get(dirString);
    		if(Files.notExists(dirPath)) {
    			try {
    				Files.createDirectories(dirPath);
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}
    		return dirString;
    	}
    	
    	public void writeToFile() throws IOException{
    		String fileName = createFile();
    		Path myFilePath = Paths.get(fileName);//Path myFilePath = Paths.get("myFile.txt");
    		File myFile = myFilePath.toFile();
    		//write data to the file
    		//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFile)));//open an output stream
    		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFile,true)));//true will prevent the 
    																						   //overwriting of existing
    																						   //lines in the text file.
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y")) {
    			Scanner input = new Scanner(System.in);
    			System.out.println("Enter a sentence of text to add a line to the " + myFile + " file:");
    			String text = input.nextLine();
    			out.println(text);
    			System.out.print("Do you want to add another line?(y/n)  ");
    			choice = input.nextLine();
    			System.out.println();
    		}
    		out.close();//flush data to the file and close the output stream
    	}	
    	
    	
    	
    	public void readFile() throws IOException {
    		String fileName = createFile();
    		System.out.println("The retrieved fileName string is: " + fileName);
    		Path myFilePath = Paths.get(fileName);
    		System.out.println("The file path is: " + myFilePath + "\n");
    		if(Files.exists(myFilePath)){//prevent the FileNotFoundException
    			File theFile = myFilePath.toFile();
    			System.out.println("File does exist. the path is: " + myFilePath.toAbsolutePath() + "\n");
    			try(BufferedReader in = new BufferedReader(new FileReader(theFile))){//open an input stream
    				String line = in.readLine();
    				while(line != null) {//prevent the EOFException
    					System.out.println(line);
    					line = in.readLine();
    				}
    				in.close();
    				System.out.println();
    			}catch(IOException e) {
    				System.out.println(e);
    			}
    		}else {
    			System.out.println(myFilePath.toAbsolutePath() + " doesn't exist");
    		}
    	}
    	
    	public void deleteFile() throws IOException{
    		String fileName = createFile();
    		Path myFilePath = Paths.get(fileName);
    		System.out.println("WAIT! before we delete the file, it's in here: " + myFilePath.toAbsolutePath());
    		if(Files.exists(myFilePath)) {
    			Files.deleteIfExists(myFilePath);
    			System.out.println(fileName + " should now be gone from directory.\n");
    			System.out.println("Now that it's deleted, lets find out if the path is gone too:\n");
    			System.out.println(myFilePath.toAbsolutePath());
    		}
    		else if(Files.notExists(myFilePath)) {
    			System.out.println("File not found. Nothing to delete.\n");
    		}		
    	}	
    	
    	public void showAllFilesInDirectory() {
    		//Display all of the files in a directory (page 463)
    		String dirString = createDirectory();
    		Path dirPath = Paths.get(dirString);
    		if(Files.exists(dirPath) && Files.isDirectory(dirPath)) {
    			try {
    				System.out.println("Directory: " + dirPath.toAbsolutePath());
    				System.out.println("Files:" );
    				DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath);
    				for(Path p:dirStream) {
    					if(Files.isRegularFile(p)) {
    						System.out.println("  " + p.getFileName().toAbsolutePath());
    					}
    				}
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}//end of if files exists if statement
    	}
    
    }//end of FileIO class
    With only the writeToFile() and readFile() methods called in the main method (because the other method calls are commented out),
    here are the output results after writing to the text file once:

    Enter a sentence of text to add a line to the myTextFile.txt file:
    sentence 1
    Do you want to add another line?(y/n) y

    Enter a sentence of text to add a line to the myTextFile.txt file:
    sentence 2
    Do you want to add another line?(y/n) n

    The retrieved fileName string is: myTextFile.txt
    The file path is: myTextFile.txt

    File does exist. the path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt

    sentence 1
    sentence 2

    And here are the output results for doing that a second time:
    Enter a sentence of text to add a line to the myTextFile.txt file:
    sentence 3
    Do you want to add another line?(y/n) y

    Enter a sentence of text to add a line to the myTextFile.txt file:
    sentence 4
    Do you want to add another line?(y/n) n

    The retrieved fileName string is: myTextFile.txt
    The file path is: myTextFile.txt

    File does exist. the path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt

    sentence 1
    sentence 2
    sentence 3
    sentence 4


    As you can see from the output, sentence 3 and sentence 4 did not overwrite sentence 1 and sentence 2.
    This tells us two things:

    1. the true argument in the PrintWriter statement on line 38 is doing its job.

    2. the text file does exist in the samsExperiments package, because it still existed there when we added sentence 3 and sentence 4.

    After doing that, here's the output results when only the deleteFile() method is called:
    WAIT! before we delete the file, it's in here: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt
    myTextFile.txt should now be gone from directory.

    Now that it's deleted, lets find out if the path is gone too:

    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt

    To double check, here is the output when only the showAllFilesInDirectory() method is called:
    Directory: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\src\samsExperiments
    Files:
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\BinarySearch.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Box.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FileIO.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FixString.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\GenericsSuite.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\InnerClassTest.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Maps.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myFile.txt
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt

    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\OrderedPair.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Queue.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\RandomClass.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsArrays.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsDataStructures.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsExperimentsMain.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsThreads.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Shapes.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\temporaryDump.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\TimeZones.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\WordAppearanceCounterApp.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\WorkingTestedCodeRepository.java

    Does the program only see the path as a string, and not a path to a file?

    If the file existed for us to be able to add sentence 3 and sentence 4 to it, why is it still not showing up the the samsExperiments package hierarchy?

    How concerned should I be about it not showing up in the hierarchy if it clearly does exist in the program itself? Should it just be dismissed as merely an Eclipse IDE quirk?
    Last edited by SamJava_the_Hut; 07-08-2019 at 07:45 AM.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,995
    Rep Power
    32

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    The code needs more debug print outs:
    There isn't a printout at line 13 or line 23 to show the create method was called.
    The results of the call to deleteIfExists was not shown on line 85.

    Where is the file being written to on line 38? Needs to print the path.
    The file path is: myTextFile.txt
    The current print out only shows the filename. It needs to show the path to the file.



    the path as a string, and not a path to a file?
    The contents of a Path variable does not mean the file exists or not.
    Last edited by Norm; 07-08-2019 at 01:22 PM.
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    95
    Rep Power
    0

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    Time for an update. I fixed the problem with the deleteFile() method... well... at least when it comes to printing out all of the files in the directory.
    In the deleteFile() method, we weren't including both the directory path and the file name arguments in the Paths.get() statement:
    Java Code:
    public void deleteFile() throws IOException{
    		//String dirString = createDirectory();
    		Path fileWithPath = Paths.get(createDirectory(),fileName);
    		if(Files.exists(fileWithPath)) {
    			Files.deleteIfExists(fileWithPath);
    		}
    		else if(Files.notExists(fileWithPath)) {
    			System.out.println("File not found. Nothing to delete.\n");
    		}		
    	}
    That said, here is my new code:

    But now we have a new problem. Here's my full new code:
    FileIO.java:
    Java Code:
    package samsExperiments;
    import java.io.*;
    import java.nio.file.*;
    import java.util.Scanner;
    
    public class FileIO {
    	//It is necessary here to make the file name global and independent of a call to the createFile() function.
    	//The reason is because calling the createFile() function just to get the text file name argument could
    	//cause our existing text file to be overwritten, and we want the writeToFile() method of this program to 
    	//be able to add new lines of user inputted text while keeping the existing ones, rather than overwritting
    	//itself several times. 
    	public final String fileName = "myTextFile.txt";//make the file name be a global variable
    	
    	/*
    	public String getTextFileName() {
    		System.out.println("What do you want to name the file?");
    		Scanner file = new Scanner(System.in);
    		String fileString = file.next();//assuming the user enters "myTextFile.txt"
    		return fileString;
    	}
    	*/
    	public String createDirectory() {
    		String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    		Path dirPath = Paths.get(dirString);
    		if(Files.notExists(dirPath)) {
    			try {
    				Files.createDirectories(dirPath);
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}
    		return dirString;
    	}
    	
    	public String createFile() throws IOException{		
    		String fileString = fileName;//"myTextFile.txt"
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileString);
    		if(Files.notExists(myFilePath)) {
    			System.out.println("createFile() method now creating " + fileString + ", because it doesn't exist yet.");
    			Files.createFile(myFilePath);//create a file if it doesn't already exist
    		}
    		else {
    			System.out.println("The file " + fileString + " already exists.");
    		}
    		return fileString;//return the string corresponding to the created file itself, not the global fileName String
    	}	
    	
    	public void writeToFile() throws IOException{
    		Path myFilePath = Paths.get(fileName);//Path myFilePath = Paths.get("myFile.txt");
    		File myFile = myFilePath.toFile();
    		//write data to the file
    		//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFile)));//open an output stream
    		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFile)),true);//true will prevent the 
    																						   //overwriting of existing
    																						   //lines in the text file.
    		System.out.println("PrintWriter printing to: " + myFile + ",");
    		System.out.println("With an absolute path of: " + myFilePath + ".");
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y")) {
    			Scanner input = new Scanner(System.in);
    			System.out.println("Enter a sentence of text to add a line to the " + myFile + " file:");
    			String text = input.nextLine();
    			out.println(text);
    			System.out.print("Do you want to add another line?(y/n)  ");
    			choice = input.nextLine();
    			System.out.println();
    		}
    		out.close();//flush data to the file and close the output stream
    	}	
    	
    	public void readFile() throws IOException {
    		Path myFilePath = Paths.get(fileName);
    		System.out.println("The file path is: " + myFilePath.toAbsolutePath() + "\n");
    		if(Files.exists(myFilePath)){//prevent the FileNotFoundException
    			File theFile = myFilePath.toFile();
    			System.out.println("File does exist. the path is: " + myFilePath.toAbsolutePath() + "\n");
    			try(BufferedReader in = new BufferedReader(new FileReader(theFile))){//open an input stream
    				String line = in.readLine();
    				while(line != null) {//prevent the EOFException
    					System.out.println(line);
    					line = in.readLine();
    				}
    				in.close();
    				System.out.println();
    			}catch(IOException e) {
    				System.out.println(e);
    			}
    		}else if(Files.notExists(myFilePath)) {
    			System.out.println(myFilePath.toAbsolutePath() + " doesn't exist");
    		}
    	}
    	
    	public boolean doesFileExist(boolean fileExists) {
    		Path myFilePath = Paths.get(fileName);
    		if(Files.exists(myFilePath)) {
    			System.out.println("Yes, " + fileName + " does exist.\n");
    			fileExists = true;
    		}
    		else if(Files.notExists(myFilePath)) {
    			System.out.println("No, " + fileName + " does not exist.\n");
    			fileExists = false;
    		}
    		return fileExists;
    	}
    	
    	public void deleteFile() throws IOException{
    		//String dirString = createDirectory();
    		Path fileWithPath = Paths.get(createDirectory(),fileName);
    		if(Files.exists(fileWithPath)) {
    			Files.deleteIfExists(fileWithPath);
    		}
    		else if(Files.notExists(fileWithPath)) {
    			System.out.println("File not found. Nothing to delete.\n");
    		}		
    	}	
    	
    	public void showAllFilesInDirectory() {
    		//Display all of the files in a directory (page 463)
    		String dirString = createDirectory();
    		Path dirPath = Paths.get(dirString);
    		if(Files.exists(dirPath) && Files.isDirectory(dirPath)) {
    			try {
    				System.out.println("Directory: " + dirPath.toAbsolutePath());
    				System.out.println("Files:" );
    				DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath);
    				for(Path p:dirStream) {
    					if(Files.isRegularFile(p)) {
    						System.out.println("  " + p.getFileName().toAbsolutePath());
    					}
    				}
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}//end of if files exists if statement
    	}
    }//end of FileIO class
    I ended up having to make the fileName string a global constant, because every time I used the createFile() function call just to retrieve and supply the other functions with the fileName string argument, it just kept on re-creating and overwritting the myTextFile.txt file.

    After running only the deleteFile(), readFile(), and showAllFilesInDirectory() methods a few times, this is the output:
    File not found. Nothing to delete.

    The file path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt

    File does exist. the path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt

    sentence 1
    sentence 2
    sentence 1
    sentence 2
    sentence 1
    sentence 2

    Directory: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\src\samsExperiments
    Files:
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\BinarySearch.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Box.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FileIO.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FileIObackup.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FixString.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\GenericsSuite.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\InnerClassTest.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Maps.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\OrderedPair.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Queue.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\RandomClass.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsArrays.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsDataStructures.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsExperimentsMain.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsThreads.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Shapes.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\temporaryDump.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\TimeZones.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\WordAppearanceCounterApp.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\WorkingTestedCodeRepository.java


    As you can see, "C:\murach\java_eclipse\SamsProjects\RandomExperim ents\myTextFile.txt" no longer shows up, which is good.

    However, despite me fixing the deleteFile() method, we are also still seeing this in the output:
    File does exist. the path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt
    sentence 1
    sentence 2
    sentence 1
    sentence 2
    sentence 1
    sentence 2


    Where is that coming from? If the fileName global constant argument included in the Paths.get statement on line 74 has to do with the statement on line 76 returning true and printing the statement on line 78, how do we fix it?
    Last edited by SamJava_the_Hut; 07-09-2019 at 11:57 AM. Reason: fixed the deleteFile() method

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,995
    Rep Power
    32

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    There are still lots of code that does something with a file that does not print out the full path to the file that is it working on.
    For example:
    Java Code:
         Path myFilePath = Paths.get(fileName);  //<<<<<<<<< needs directory
            if(Files.exists(myFilePath)) {
                System.out.println("Yes, " + fileName + " does exist.\n");  // does not show full path
    There is no debug print statement here:
    Java Code:
     if(Files.exists(fileWithPath)) {
            // where is this file located?
                Files.deleteIfExists(fileWithPath);    // does this return true or false?
    Where is the print out for these two print statements? I do not see it the the posted output:
    Java Code:
            System.out.println("PrintWriter printing to: " + myFile + ",");
            System.out.println("With an absolute path of: " + myFilePath + ".");
    Where does the writeToFile write its output? Print the full path.
    Last edited by Norm; 07-09-2019 at 01:00 PM.
    If you don't understand my response, don't ignore it, ask a question.

  14. #14
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    95
    Rep Power
    0

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    Quote Originally Posted by Norm View Post
    There are still lots of code that does something with a file that does not print out the full path to the file that is it working on.
    OK Norm. Hope this is what you were looking for:

    FileIO.java:
    Java Code:
    package samsExperiments;
    import java.io.*;
    import java.nio.file.*;
    import java.util.Scanner;
    
    public class FileIO {
    	//It is necessary here to make the file name global and independent of a call to the createFile() function.
    	//The reason is because calling the createFile() function just to get the text file name argument could
    	//cause our existing text file to be overwritten, and we want the writeToFile() method of this program to 
    	//be able to add new lines of user inputted text while keeping the existing ones, rather than overwritting
    	//itself several times. 
    	public final String fileName = "myTextFile.txt";//make the file name be a global variable
    	
    	/*
    	public String getTextFileName() {
    		System.out.println("What do you want to name the file?");
    		Scanner file = new Scanner(System.in);
    		String fileString = file.next();//assuming the user enters "myTextFile.txt"
    		return fileString;
    	}
    	*/
    	public String createDirectory() {
    		String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    		Path dirPath = Paths.get(dirString);
    		if(Files.notExists(dirPath)) {
    			try {
    				Files.createDirectories(dirPath);
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}
    		return dirString;
    	}
    	
    	public String createFile() throws IOException{		
    		String fileString = fileName;//"myTextFile.txt"
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileString);
    		if(Files.notExists(myFilePath)) {
    			System.out.println("createFile() method now creating " + fileString + ", because it doesn't exist yet.");
    			Files.createFile(myFilePath);//create a file if it doesn't already exist
    		}
    		else {
    			System.out.println("The file " + fileString + " already exists.");
    		}
    		return fileString;//return the string corresponding to the created file itself, not the global fileName String
    	}
    	
    	public boolean doesFileExist() {
    		boolean fileExists = false;
    		Path myFilePath = Paths.get(fileName);
    		if(Files.exists(myFilePath)) {
    			System.out.println("Yes, " + fileName + " does exist.");
    			System.out.println("The full path is: " + myFilePath.toAbsolutePath());
    			fileExists = true;
    		}
    		else if(Files.notExists(myFilePath)) {
    			System.out.println("No, " + fileName + " does not exist.\n");
    			fileExists = false;
    		}
    		return fileExists;
    	}
    	
    	public void writeToFile() throws IOException{
    		boolean weHaveAFileToWriteTo = doesFileExist();
    		if(weHaveAFileToWriteTo == false) {
    			System.out.println("We don't have a file to write to. Aborting writeToFile() method now.");
    			return;
    		}
    		else {
    			Path myFilePath = Paths.get(fileName);//Path myFilePath = Paths.get("myTextFile.txt");
    			File myFile = myFilePath.toFile();
    			//write data to the file
    			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFile)),true);//true will prevent the 
    																							   //overwriting of existing
    																							   //lines in the text file.
    			System.out.println("PrintWriter printing to: " + myFile + ",");
    			System.out.println("With an absolute path of: " + myFilePath.toAbsolutePath() + ".\n");
    			String choice = "y";
    			while(choice.equalsIgnoreCase("y")) {
    				Scanner input = new Scanner(System.in);
    				System.out.println("Enter a sentence of text to add a line to the " + myFile + " file:");
    				String text = input.nextLine();
    				out.println(text);
    				System.out.println(text + "printed to our file in " + myFilePath.toAbsolutePath() + "\n");
    				System.out.print("Do you want to add another line?(y/n)  ");
    				choice = input.nextLine();
    				System.out.println();
    			}
    			out.close();//flush data to the file and close the output stream
    		}
    		
    	}	
    	
    	public void readFile() throws IOException {
    		boolean weHaveAFileToReadFrom = doesFileExist();
    		if(weHaveAFileToReadFrom == false) {
    			System.out.println("We don't have a file to read from. Aborting readFile() method now.");
    			return;
    		}
    		else {
    			Path myFilePath = Paths.get(fileName);
    			if(Files.exists(myFilePath)){//prevent the FileNotFoundException
    				File theFile = myFilePath.toFile();
    				System.out.println("File does exist. the path is: " + myFilePath.toAbsolutePath() + "\n");
    				try(BufferedReader in = new BufferedReader(new FileReader(theFile))){//open an input stream
    					String line = in.readLine();
    					while(line != null) {//prevent the EOFException
    						System.out.println(line);
    						line = in.readLine();
    					}
    					in.close();
    					System.out.println();
    				}catch(IOException e) {
    					System.out.println(e);
    				}
    			}else if(Files.notExists(myFilePath)) {
    				System.out.println(myFilePath.toAbsolutePath() + " doesn't exist");
    			}
    		}
    	}
    	
    	
    	
    	public void deleteFile() throws IOException{
    		String dirString = createDirectory();
    		Path pathAlone = Paths.get(fileName);
    		Path fileWithPath = Paths.get(dirString,fileName);
    		if(Files.exists(fileWithPath)) {
    			System.out.println("Now deleting " + fileName + " from " +
    							   pathAlone.toAbsolutePath());
    			System.out.println(Files.deleteIfExists(fileWithPath));//should print out "true"
    			Files.deleteIfExists(fileWithPath );
    			System.out.println(Files.deleteIfExists(fileWithPath));//should print out "false"
    		}
    		else if(Files.notExists(fileWithPath)) {
    			System.out.println("File not found. Nothing to delete.\n");
    		}		
    	}	
    	
    	public void showAllFilesInDirectory() {
    		//Display all of the files in a directory (page 463)
    		String dirString = createDirectory();
    		Path dirPath = Paths.get(dirString);
    		if(Files.exists(dirPath) && Files.isDirectory(dirPath)) {
    			try {
    				System.out.println("Directory: " + dirPath.toAbsolutePath());
    				System.out.println("Files:" );
    				DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath);
    				for(Path p:dirStream) {
    					if(Files.isRegularFile(p)) {
    						System.out.println("  " + p.getFileName().toAbsolutePath());
    					}
    				}
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}//end of if files exists if statement
    	}
    }//end of FileIO class
    SamsExperimentsMain.java:
    Java Code:
    package samsExperiments;
    
    import java.util.Scanner;
    import java.util.Arrays;
    import java.util.Calendar;
    import java.util.Collections;
    import java.util.Deque;
    
    import SortingAlgorithms.*;
    import customExceptions.BuiltInExceptions;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Vector;
    import java.util.Hashtable;
    import java.util.Map;
    import java.util.Queue;
    import java.util.TreeMap;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.ListIterator;
    import java.util.Locale;
    import java.time.DayOfWeek;
    import java.time.LocalDate;//yyyy-mm-dd
    import java.time.LocalTime;//hh-mm-ss-nn
    import java.time.Month;
    import java.time.temporal.ChronoUnit;
    import java.time.LocalDateTime;//yyyy-mm-dd-hh-ss-nn
    import java.io.IOException;
    import java.time.*;
    
    public class SamsExperimentsMain {
    	
    	public static void main(String[] args){
    		
    		
    		// C:\murach\java_eclipse\SamsProjects\RandomExperiments\src\samsExperiments
    		FileIO fio = new FileIO();		
    
    		try {
    			
    			//fio.getFileName();
    			
    			//fio.createFile();			
    			
    			//fio.createDirectory();// the createFile() method already calls this.	
    			
    			fio.doesFileExist();
    			
    			//fio.writeToFile();
    			
    			//fio.readFile();			
    			
    			//fio.deleteFile();			
    			
    			fio.showAllFilesInDirectory();
    			
    		} catch (IOException e) {
    			e.printStackTrace();
    			System.out.println(e);
    		}
    		
    		
    	}//end of main method
    	
    }//end of class
    After using the deleteFile() method once, and then running the program again calling only the deleteFile() and showAllFilesInDirectory() methods, this was the output:
    File not found. Nothing to delete.

    Directory: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\src\samsExperiments
    Files:
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\BinarySearch.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Box.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FileIO.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FileIObackup.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FixString.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\GenericsSuite.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\InnerClassTest.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Maps.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\OrderedPair.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Queue.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\RandomClass.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsArrays.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsDataStructures.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsExperimentsMain.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsThreads.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Shapes.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\temporaryDump.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\TimeZones.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\WordAppearanceCounterApp.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\WorkingTestedCodeRepository.java


    And then after that I ran the program again only using doesFileExist(), readFile() and showAllFilesInDirectory() methods, and this was the output:
    Yes, myTextFile.txt does exist.
    The full path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt
    Yes, myTextFile.txt does exist.
    The full path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt
    File does exist. the path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt

    sentence 3

    Directory: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\src\samsExperiments
    Files:
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\BinarySearch.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Box.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FileIO.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FileIObackup.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\FixString.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\GenericsSuite.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\InnerClassTest.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Maps.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\OrderedPair.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Queue.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\RandomClass.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsArrays.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsDataStructures.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsExperimentsMain.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\SamsThreads.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\Shapes.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\temporaryDump.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\TimeZones.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\WordAppearanceCounterApp.java
    C:\murach\java_eclipse\SamsProjects\RandomExperime nts\WorkingTestedCodeRepository.java


    In this circumstance, we shouldn't have seen "Yes, myTextFile.txt does exist." in the output.

    I'm suspecting that because the fileName string in FileIO.java has global scope, and thus automatically gets passed into the Paths.get(fileName) statement on line 52, it makes the program think that there is a file and a path, so the doesFileExist() method always returns true. What do you guys think? Is there a better way to pass the fileName string non-globally without getting it by calling the createFile() method each time we need the fileName string?

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,995
    Rep Power
    32

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    Yes, myTextFile.txt does exist.
    The full path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt
    Yes, myTextFile.txt does exist.
    The full path is: C:\murach\java_eclipse\SamsProjects\RandomExperime nts\myTextFile.txt
    What is wrong with that output?
    There is no print out saying that the file was deleted, so if the file exists, then I'd expect to see those print outs.

    What I'd expect to see could be like this:
    The file D:\temp\theFile.txt exists
    The file D:\temp\theFile.txt was deleted
    The file D:\temp\theFile.txt does not exist

    The code still has several calls to Path.get() that do not include the directory which means they are looking at a different place for the file than the calls that have a directory
    Java Code:
       Path pathAlone = Paths.get(fileName);                // uses the local directory
      Path fileWithPath = Paths.get(dirString,fileName);  // uses dirString directory
    The results are that there are two separate files the program is looking at in two different directories.
    Last edited by Norm; 07-10-2019 at 01:00 PM.
    If you don't understand my response, don't ignore it, ask a question.

  16. #16
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    95
    Rep Power
    0

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    Quote Originally Posted by Norm View Post
    The code still has several calls to Path.get() that do not include the directory which means they are looking at a different place for the file than the calls that have a directory
    Java Code:
       Path pathAlone = Paths.get(fileName);                // uses the local directory
      Path fileWithPath = Paths.get(dirString,fileName);  // uses dirString directory
    The results are that there are two separate files the program is looking at in two different directories.
    Norm, you're the man!
    Remember how I had
    Java Code:
    Path myFilePath = Paths.get(dirString,fileName);
    for the deleteFile() method only?
    Well, I applied that to the other methods, and now they work just fine.
    Java Code:
    package samsExperiments;
    import java.io.*;
    import java.nio.file.*;
    import java.util.Scanner;
    
    public class FileIO {
    	//It is necessary here to make the file name global and independent of a call to the createFile() function.
    	//The reason is because calling the createFile() function just to get the text file name argument could
    	//cause our existing text file to be overwritten, and we want the writeToFile() method of this program to 
    	//be able to add new lines of user inputted text while keeping the existing ones, rather than overwritting
    	//itself several times. 
    	public final String fileName = "myTextFile.txt";//make the file name be a global variable
    	
    	/*
    	public String getTextFileName() {
    		System.out.println("What do you want to name the file?");
    		Scanner file = new Scanner(System.in);
    		String fileString = file.next();//assuming the user enters "myTextFile.txt"
    		return fileString;
    	}
    	*/
    	public String createDirectory(){
    		String dirString = "C:\\murach\\java_eclipse\\SamsProjects\\RandomExperiments\\src\\samsExperiments";
    		Path dirPath = Paths.get(dirString);
    		if(Files.notExists(dirPath)) {
    			try {
    				Files.createDirectories(dirPath);
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}
    		return dirString;
    	}
    	
    	public String createFile() throws IOException{		
    		String fileString = fileName;//"myTextFile.txt"
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileString);
    		if(Files.notExists(myFilePath)) {
    			System.out.println("createFile() method now creating " + fileString + ", because it doesn't exist yet.");
    			Files.createFile(myFilePath);//create a file if it doesn't already exist
    			System.out.println(fileString + "created in " + myFilePath);
    		}
    		else {
    			System.out.println("The file " + fileString + " already exists.");
    		}
    		return fileString;//return the string corresponding to the created file itself, not the global fileName String
    	}
    	
    	public boolean doesFileExist() {
    		boolean fileExists = false;
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileName);
    		System.out.println("doesFileExist() dirString = " + dirString);
    		System.out.println("doesFileExist() myFilePath = " + myFilePath);
    		System.out.println("doesFileExist() myFilePath = " + myFilePath.toAbsolutePath());
    		
    		if(Files.exists(myFilePath)) {
    			System.out.println("Yes, " + fileName + " does exist.");
    			System.out.println("The full path is: " + myFilePath.toAbsolutePath());
    			fileExists = true;
    		}
    		else if(Files.notExists(myFilePath)) {
    			System.out.println("No, " + fileName + " does not exist.\n");
    			fileExists = false;
    		}
    		return fileExists;
    	}
    	
    	public void writeToFile() throws IOException{
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileName);
    		System.out.println("writeToFile() dirString = " + dirString);
    		System.out.println("writeToFile() myFilePath = " + myFilePath);
    		System.out.println("writeToFile() myFilePath = " + myFilePath.toAbsolutePath());
    		boolean weHaveAFileToWriteTo = doesFileExist();
    		System.out.println(weHaveAFileToWriteTo);
    		if(weHaveAFileToWriteTo == false) {
    			System.out.println("We don't have a file to write to. Aborting writeToFile() method now.");
    			return;
    		}
    		else {
    			//Path myFilePath = Paths.get(fileName);//Path myFilePath = Paths.get("myTextFile.txt");
    			File myFile = myFilePath.toFile();
    			//write data to the file
    			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(myFile,true)));
    			System.out.println("PrintWriter printing to: " + myFile + ",");
    			System.out.println("With an absolute path of: " + myFilePath.toAbsolutePath() + ".\n");
    			String choice = "y";
    			while(choice.equalsIgnoreCase("y")) {
    				Scanner input = new Scanner(System.in);
    				System.out.println("Enter a sentence of text to add a line to the " + myFile + " file:");
    				String text = input.nextLine();
    				out.println(text);
    				System.out.println(text + "printed to our file in " + myFilePath.toAbsolutePath() + "\n");
    				System.out.print("Do you want to add another line?(y/n)  ");
    				choice = input.nextLine();
    				System.out.println();
    			}
    			out.close();//flush data to the file and close the output stream
    		}
    		
    	}	
    	
    	public void readFile() throws IOException {
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileName);
    		System.out.println("readFile() dirString = " + dirString);
    		System.out.println("readFile() myFilePath = " + myFilePath);
    		System.out.println("readFile() myFilePath = " + myFilePath.toAbsolutePath());
    		boolean weHaveAFileToReadFrom = doesFileExist();
    		System.out.println(weHaveAFileToReadFrom);
    		if(weHaveAFileToReadFrom == false) {
    			System.out.println("We don't have a file to read from. Aborting readFile() method now.");
    			return;
    		}
    		else {
    			//Path myFilePath = Paths.get(fileName);
    			if(Files.exists(myFilePath)){//prevent the FileNotFoundException
    				File theFile = myFilePath.toFile();
    				System.out.println("File does exist. the path is: " + myFilePath.toAbsolutePath() + "\n");
    				try(BufferedReader in = new BufferedReader(new FileReader(theFile))){//open an input stream
    					String line = in.readLine();
    					while(line != null) {//prevent the EOFException
    						System.out.println(line);
    						line = in.readLine();
    					}
    					in.close();
    					System.out.println();
    				}catch(IOException e) {
    					System.out.println(e);
    				}
    			}else if(Files.notExists(myFilePath)) {
    				System.out.println(myFilePath.toAbsolutePath() + " doesn't exist");
    			}
    		}
    	}	
    	
    	public void deleteFile() throws IOException{
    		String dirString = createDirectory();
    		Path myFilePath = Paths.get(dirString,fileName);
    		System.out.println("deleteFile() dirString = " + dirString);
    		System.out.println("deleteFile() pathAlone = " + myFilePath);
    		System.out.println("deleteFile() pathAlone = " + myFilePath.toAbsolutePath());
    		if(Files.exists(myFilePath)) {
    			System.out.println("Now deleting " + fileName + " from " +
    					myFilePath.toAbsolutePath());			
    			Files.deleteIfExists(myFilePath );
    			if(Files.deleteIfExists(myFilePath) == false) {
    				System.out.println(fileName + " From " + myFilePath + " successfully deleted.\n");
    			}
    			System.out.println("File existence set to " + Files.deleteIfExists(myFilePath));
    		}
    		else if(Files.notExists(myFilePath)) {
    			System.out.println("File not found. Nothing to delete.\n");
    		}		
    	}	
    	
    	public void showAllFilesInDirectory() throws IOException{
    		//Display all of the files in a directory (page 463)
    		String dirString = createDirectory();
    		Path dirPath = Paths.get(dirString);
    		if(Files.exists(dirPath) && Files.isDirectory(dirPath)) {
    			try {
    				System.out.println("Directory: " + dirPath.toAbsolutePath());
    				System.out.println("Files:" );
    				DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath);
    				for(Path p:dirStream) {
    					if(Files.isRegularFile(p)) {
    						System.out.println("  " + p.getFileName().toAbsolutePath());
    					}
    				}
    			}
    			catch(IOException e) {
    				System.out.println(e);
    			}
    		}//end of if files exists if statement
    	}
    }//end of FileIO class

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,995
    Rep Power
    32

    Default Re: My package hierarchy looks right, I'm having syntax issues with File IO.

    If the debug print outs had always printed the full path to the files that were being worked on, the problem would have been seen long ago.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. How to package a .class file into a .jar file?
    By Zarah in forum New To Java
    Replies: 3
    Last Post: 04-30-2016, 11:06 AM
  2. Replies: 0
    Last Post: 04-22-2014, 10:41 PM
  3. Importing package syntax
    By Lowest0ne in forum New To Java
    Replies: 1
    Last Post: 11-06-2012, 04:43 PM
  4. issues while saving a '.java' file in the bin.
    By akshayshukla in forum New To Java
    Replies: 3
    Last Post: 04-29-2012, 03:02 PM
  5. Issues with parsing huge file
    By aneuryzma in forum New To Java
    Replies: 2
    Last Post: 03-29-2011, 03:02 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •