Jump to content

Java Help


nandrolone

Recommended Posts

Remove/move post if irrelevant

 

TASK: 

Exercise 3 - Copy Program Write a program that allows you to create duplicate/copy of files. Your program should have the following properties:

• Allow the user to specify the file that is to be copied.

• Allow the user to specify the destination to where the file is to be copied.

• Warn users when a file is being overwritten because of copying. This will happen if the destination file already exists. In such cases, you can ask the user whether they want to continue with the writing or abort. • Handle both binary and text files. Take extra care about which streams you need if you want to handle both binary and text files.

• You should also handle the usual errors, for example when a user wants to copy a file that doesn’t exist.

 

Current code: 

import java.io.*; 
import java.util.Scanner;
public class Confidential 


             public static void main(String args[])throws IOException  { 
                 try{
              FileWriter fw = new FileWriter("Confidential.txt");
              PrintWriter pw = new PrintWriter(fw);
              pw.println("Lewis Ovenden 1607557");
              
              pw.close();
              fw.close();
              
 
              FileInputStream Fread =new FileInputStream("Confidential.txt");
              
              
              FileOutputStream Fwrite=new FileOutputStream("Confidential1.txt") ;  
               
              int input=0;
              
              Scanner scanner = new Scanner (System.in);
              System.out.print("Which file do you want to copy? "); 
              String name = scanner.next(); 
              System.out.print("Where do you want the file to be copied?  ");
              String fileName = scanner.next(); 
              scanner.close(); 
              while (input != -1) {
                
                  input = Fread.read();
                  
                  if (input != -1)
                      Fwrite.write(input);                              
                
                  }
              
              
              Fwrite.close();
              Fread.close(); 
               
                 } catch (IOException e) {
                     System.out.println("Error -- " + e.toString()); 
         } 
}
}

 

Struggling to be able to use scanner input to be able to interact with user to copy the file (file gets copied regardless of input atm)

Link to comment
Share on other sites

23 minutes ago, nandrolone said:

FileInputStream Fread =new FileInputStream("Confidential.txt");

You want to define Fread after the scanner and inplace of "Confidential.txt" you will want to give it your new file location that you recieved from the user(after you ran all of the needed checks on the input).

Link to comment
Share on other sites

17 minutes ago, HunterRS said:

You want to define Fread after the scanner and inplace of "Confidential.txt" you will want to give it your new file location that you recieved from the user(after you ran all of the needed checks on the input).

I have done the first bit, giving a file location that is received from the user how can i call that? 

Link to comment
Share on other sites

46 minutes ago, nandrolone said:

I have done the first bit, giving a file location that is received from the user how can i call that? 

That is exactly what I explained how to do...

 


              
              
              FileOutputStream Fwrite=new FileOutputStream("Confidential1.txt") ;  
               
              int input=0;
              
              Scanner scanner = new Scanner (System.in);
              System.out.print("Which file do you want to copy? "); 
              String name = scanner.next(); 
              System.out.print("Where do you want the file to be copied?  ");
              String fileName = scanner.next(); 

FileInputStream Fread =new FileInputStream(fileName);

              scanner.close(); 

 

8 minutes ago, d0zza said:

Osbot only allows writing/reading in the osbot/data directory. You can easily get this directory for any user/computer by calling getDirectoryData();

pretty sure it is a HW assignment 

 

Edited by HunterRS
Link to comment
Share on other sites

1 minute ago, HunterRS said:


              
              
              FileOutputStream Fwrite=new FileOutputStream("Confidential1.txt") ;  
               
              int input=0;
              
              Scanner scanner = new Scanner (System.in);
              System.out.print("Which file do you want to copy? "); 
              String name = scanner.next(); 
              System.out.print("Where do you want the file to be copied?  ");
              String fileName = scanner.next(); 

FileInputStream Fread =new FileInputStream(fileName);

              scanner.close(); 

 

pretty sure it is a HW assignment 

 

Yeah it's coursework assignment from uni, appreciate any input from you both i'm a noob at java 

Link to comment
Share on other sites

Just now, nandrolone said:

Yeah it's coursework assignment from uni, appreciate any input from you both i'm a noob at java 

this isn't even java buddy :), this is just simple logic.

You goal is to open a file that the user asked for...

Lets write out our steps:
1. receive the file's location/name

2. check the string we received

3. open the file with the string.

Link to comment
Share on other sites

4 minutes ago, HunterRS said:

this isn't even java buddy :), this is just simple logic.

You goal is to open a file that the user asked for...

Lets write out our steps:
1. receive the file's location/name

2. check the string we received

3. open the file with the string.

Maybe i am misunderstanding, the goal of the task is to be able to copy a file that the user has requested, and copy it to the destination of the users choice, correct?

Link to comment
Share on other sites

2 minutes ago, nandrolone said:

Maybe i am misunderstanding, the goal of the task is to be able to copy a file that the user has requested, and copy it to the destination of the users choice, correct?

that is correct, but inorder to copy the file you must first open it correct?

for the whole task you need to:

1. Get file name

2. check if file exists etc.

3. check if the new location (the one you are moving the file too) exists so you can warn the user if it does.

4. read the file from the location

5. write the file to the new location

Edited by HunterRS
Link to comment
Share on other sites

26 minutes ago, HunterRS said:

that is correct, but inorder to copy the file you must first open it correct?

for the whole task you need to:

1. Get file name

2. check if file exists etc.

3. check if the new location (the one you are moving the file too) exists so you can warn the user if it does.

4. read the file from the location

5. write the file to the new location

Okay i'm understanding

 

Which file do you want to copy? Confidential.txt
Where do you want the file to be copied?  C:\Users\imenu\Documents
Error -- java.io.FileNotFoundException: C:\Users\imenu\Documents (Access is denied)

 

Got this in console, what would be the reason?

import java.io.*; 
import java.util.Scanner;
public class Confidential 


             public static void main(String args[])throws IOException  { 
                 try{
              FileWriter fw = new FileWriter("Confidential.txt");
              PrintWriter pw = new PrintWriter(fw);
              pw.println("Lewis Ovenden 1607557");
              
              pw.close();
              fw.close();

              
              FileOutputStream Fwrite=new FileOutputStream("Confidential1.txt") ;  
               
              int input=0;
              
              Scanner scanner = new Scanner (System.in);
              System.out.print("Which file do you want to copy? "); 
              String name = scanner.next(); 
              System.out.print("Where do you want the file to be copied?  ");
              String fileName = scanner.next(); 

FileInputStream Fread =new FileInputStream(fileName);

              scanner.close();
               
              while (input != -1) {
                
                  input = Fread.read();
                  
                  if (input != -1)
                      Fwrite.write(input);                              
                
                  }
              
              
              Fwrite.close();
              Fread.close(); 
               
                 } catch (IOException e) {
                     System.out.println("Error -- " + e.toString()); 
         } 
}
}

 

 

 

 

Link to comment
Share on other sites

15 minutes ago, nandrolone said:

Okay i'm understanding

 

Which file do you want to copy? Confidential.txt
Where do you want the file to be copied?  C:\Users\imenu\Documents
Error -- java.io.FileNotFoundException: C:\Users\imenu\Documents (Access is denied)

 

Got this in console, what would be the reason?

import java.io.*; 
import java.util.Scanner;
public class Confidential 


             public static void main(String args[])throws IOException  { 
                 try{
              FileWriter fw = new FileWriter("Confidential.txt");
              PrintWriter pw = new PrintWriter(fw);
              pw.println("Lewis Ovenden 1607557");
              
              pw.close();
              fw.close();

              
              FileOutputStream Fwrite=new FileOutputStream("Confidential1.txt") ;  
               
              int input=0;
              
              Scanner scanner = new Scanner (System.in);
              System.out.print("Which file do you want to copy? "); 
              String name = scanner.next(); 
              System.out.print("Where do you want the file to be copied?  ");
              String fileName = scanner.next(); 

FileInputStream Fread =new FileInputStream(fileName);

              scanner.close();
               
              while (input != -1) {
                
                  input = Fread.read();
                  
                  if (input != -1)
                      Fwrite.write(input);                              
                
                  }
              
              
              Fwrite.close();
              Fread.close(); 
               
                 } catch (IOException e) {
                     System.out.println("Error -- " + e.toString()); 
         } 
}
}

 

 

 

 

Maybe you dont have priviliges to that location?

Try starting by copying it to the same folder under a differant name

Link to comment
Share on other sites

I waited before now because I don't want to do your work for you. I did release a thread on how to copy a script (packed in a jar file) to OSBot's script folder, which would help you find out some of that stuff. But in relation to your assignment, I've wrote the following:

Note: the "Take extra care about which streams you need if you want to handle both binary and text files" has sort of been addressed in that, the file you chose to copy will have its type factored into the the new file when copying, because I've used JFileChooser.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Test {
	
	public static void main(String[] args) throws IllegalArgumentException, FileNotFoundException, IOException {
		
		File source;
		File destination;
		String fileExtension;
		FileFilter fileFilter;
		
		// get source
		
		source = selectFileToBeCoppied();
		
		if (source == null) {
			System.err.println("No source file selected!");
			System.exit(0);
		}
		
		// create file filter
		
		fileExtension = getFileExtension(source);
		
		fileFilter = createFileFilter(fileExtension);
		
		// get destination
		
		destination = selectDestinationToCopyTo(fileFilter);
		
		if (destination == null) {
			System.err.println("No destination file selected!");
			System.exit(0);
		}
		
		// make sure destination includes extension (because users sometimes forget to include it in themselves)
		
		if (fileExtension != null && !destination.getName().endsWith("." + fileExtension)) {
			
			destination = new File(destination.getParentFile(), destination.getName() + "." + fileExtension);
		}
		
		// hope destination file doesn't exist OR request permission to overwrite file
		
		if (!destination.exists() || requestPermissionToOverwriteFile()) {
			
			copyFiles(source, destination);
		}
	}

	/**
	 * Allow the user to specify the file that is to be copied
	 * 
	 * @return selectedFile
	 */
	private static File selectFileToBeCoppied() {
		
		File selectedFile = null;
		JFileChooser fileChooser = new JFileChooser();
		
		if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			selectedFile = fileChooser.getSelectedFile();
		}
		
		return selectedFile;
	}

	/**
	 * If you chose to copy a text file (.txt) then it makes sense to save it as a
	 * text file also. Conversely, if the file has no file extension, then we want
	 * to also copy it without an extension.
	 * 
	 * @param fileExtension
	 *            - file extension
	 * @return fileFilter
	 */
	private static FileFilter createFileFilter(String fileExtension) {
		
		FileFilter fileFilter = null;
		
		if (fileExtension != null) {
			
			fileFilter = new FileNameExtensionFilter(fileExtension, fileExtension);
			
		} else {
			
			fileFilter = new FileFilter() {
				
				@Override
				public String getDescription() {
					
					return "No file type selected";
				}
				
				@Override
				public boolean accept(File f) {
					
					return !f.getName().contains(".");
				}
			};
		}
		
		return fileFilter;
	}
	
	/**
	 * Extract the extension of a file
	 * 
	 * @param file
	 *            - File to analyse
	 * @return fileExtension
	 */
	private static String getFileExtension(File file) {
		String fileExtension = null;
		String fileName = file.getName();
		int dotIndex = fileName.lastIndexOf(".");
		if (dotIndex >= 0) {
			fileExtension = fileName.substring(dotIndex + 1);
		}
		return fileExtension;
	}
	
	/**
	 * Allow the user to specify the destination to where the file is to be copied
	 * 
	 * @return selectedFile
	 */
	private static File selectDestinationToCopyTo(FileFilter fileFilter) {
		
		File selectedFile = null;
		JFileChooser fileChooser = new JFileChooser();
		
		fileChooser.setFileFilter(fileFilter);
		
		if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
			
			selectedFile = fileChooser.getSelectedFile();
		}
		
		return selectedFile;
	}
	
	/**
	 * Warn users when a file is being overwritten because of copying. This will
	 * happen if the destination file already exists. In such cases, you can ask the
	 * user whether they want to continue with the writing or abort.
	 * 
	 * @return <tt>User has granted permission to overwrite a file</tt>
	 */
	private static boolean requestPermissionToOverwriteFile() {
		return JOptionPane.showConfirmDialog(null, "File already exists.\nDo you want to replace it?", "Confirm",
				JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION;
	}
	
	/**
	 * Handle both binary and text files. Take extra care about which streams you
	 * need if you want to handle both binary and text files
	 * 
	 * @param source - File source (file/folder)
	 * @param destination - File destination
	 * @throws IllegalArgumentException - Bad arguments
	 * @throws FileNotFoundException - No file found
	 * @throws IOException - Failed to copy
	 */
	private static void copyFiles(File source, File destination)
			throws IllegalArgumentException, FileNotFoundException, IOException {
		
		byte[] buffer;
		int length;
		
		if (source.equals(destination)) {
			
			throw new IllegalArgumentException("Source and destination files cannot be the same");
			
		} else {
			
			buffer = new byte[1024];
			
			try (
					FileInputStream in = new FileInputStream(source);
					FileOutputStream out = new FileOutputStream(destination);
					) {
				
				while ((length = in.read(buffer)) > 0) {
					
					out.write(buffer, 0, length);
					
				}
			}
		}
		
	}
	
}

 

  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...