Java program that program CopyFile that copies one file to another - java

I want to write a program that copies one file to another. I got my program to execute and run but nothing happens! I have no errors to go by so I'm stuck and don't know what to do! It doesn't create the files or copies them into one file.
Here's the command I typed:
java CopyFile report.txt report.sav
The program should create another copy of the file report.txt in report.sav. Your program should print the following error message for inappropriate number of input arguments (for e.g., java CopyFile report.txt):
Here's my code:
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
/**
This program copies one file to another.
*/
public class CopyFile
{
public static void main(String[] args) throws FileNotFoundException
{
if (args.length != 2)
{
System.out.println("Usage: java CopyFile fromFile toFile");
return;
}
String source = args[0];
}
}

use this-
Files.copy(source.toPath(), dest.toPath());
This method you can find in java 7.
Refer to this link for other ways-
http://examples.javacodegeeks.com/core-java/io/file/4-ways-to-copy-file-in-java/

You can use FileUtils from Apache IOCommons
FileUtils.copyFile(src, dest)

Related

Storing String input in a file

Ok, before anyone starts flaming me for asking "dumb" questions, please note that I have pretty much exhausted every other option that I know of and come up empty handed. Still if you feel like it, please go ahead and downvote/report this question.
Now, for those that care
I am trying to take a String input from user and store it into a file Text.txt which will be created in the current working directory.
Following is the code
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Encryption {
public static void main(String[] args) throws Exception {
System.out.println("Enter a String you wish to encrypt : ");
new BufferedWriter(new FileWriter(".\\Text.txt")).write(new Scanner(System.in).nextLine());
System.out.println("Done");
}
}
My problem is, the file is getting generated at the correct destination, but is always empty. I have tried it on multiple JDK versions and on different machines. Still getting the blank text file.
Please tell me, what is it that I am doing wrong.
You are not closing with .close() the BufferedWriter (which would then flush the last buffer and close the file).
You can however do that task in new style:
Files.write(Paths.get(".\\Text.txt"),
Arrays.asList(new Scanner(System.in).nextLine()),
Charset.defaultCharset());
Otherwise you would need to introduce a variable, and gone is the one-liner.
Some changes i made your code to work
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Encryption {
public static void main(String[] args) throws Exception {
System.out.println("Enter a String you wish to encrypt : ");
String text = new Scanner(System.in).nextLine();
BufferedWriter b = new BufferedWriter(new FileWriter(".\\Text.txt"));
b.write(text);
b.close();
System.out.println("Done");
}
}

Error changed system cannot find file specified

package q1;
import java.io.FileNotFoundException;
import java.util.ArrayList;
/**
* <p>This is where you put your description about what this class does. You
* don't have to write an essay but you should describe exactly what it does.
* Describing it will help you to understand the programming problem better.</p>
*
* #author Your Name goes here
* #version 1.0
*/
public class Household {
/**
* <p>This is the main method (entry point) that gets called by the JVM.</p>
*
* #param args command line arguments.
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// your code will go here!!!
Survey s1 = new Survey();
s1.getSurveyList();
System.out.println();
}
};
-------------------------------------------------------------------------------------------
package q1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Survey {
ArrayList<Integer> surveyList = new ArrayList<Integer>();
public Survey(){
}
public ArrayList<Integer> getSurveyList() throws FileNotFoundException{
Scanner sc = new Scanner(new File("survey.txt"));
while (sc.hasNextLine()) {
sc.useDelimiter(" ");
int i = sc.nextInt();
surveyList.add(i);
}
System.out.println(surveyList.get(0));
sc.close();
return surveyList;
}
}
Now it says that the system cannot find the file specified. Not sure how to use the File class because it is the first time I have had to do it.
Any ideas? Also how would one format the output of the text file so that it displays it in a table? Is there some method that does that?
The error "Could not find main class" has nothing to do with the way you are using the File or Scanner class. It sounds like your classpath is wrong. Ensure that your project root is configured correctly. You could try to use this tutorial for using Eclipse for a reference on how to set up your project correctly. If you are not using an IDE, check out the contents of the file you are running and make sure the correct information is in there. It would help a lot if you could specify your question a lot more such as which operating system are you using, are you using an IDE (if yes, which one), are you compiling it as a jar file or are you running it from a directory with class files... etc.
Changed Array to Double instead of Integer and changed the scanner line to this:
Scanner sc = new Scanner(
new File("src" + File.separator + "survey.txt"));

how to copy a file only if it does not exist in the to directory java

I have searched pretty thoroughly and I'm fairly certain that no one has asked this question. However, this may be because this is completely the wrong way to go about this. I once wrote an effective java program that copied files from one directory to another. If the file already existed in the corresponding directory it would be caught with an exception and renamed. I want to use this program for another application, and for this I want it to do nothing when the exception is caught, simply continue on with the program without copying that file. I will be using this to fix approximately 18gb of files when it works, if it even printed one character when the exception was caught it would be extremely inefficient. This is the code I have so far:
import java.nio.file.*;
import java.io.IOException;
public class Sync
{
public static void main(String[] args)
{
String from=args[0];
Path to=FileSystems.getDefault().getPath(args[1]);
copyFiles(from, to);
}
public static void copyFiles(String from, Path to)
{
try(DirectoryStream<Path> files= Files.newDirectoryStream(FileSystems.getDefault().getPath(from)))
{
for(Path f:files)
{
Files.copy(f, to.resolve(f.getFileName()));
System.out.println(" "+f.getFileName()+" copied ");
}
}
catch(FileAlreadyExistsException e)
{
//not sure
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Is there a way to use FileAlreadyExistsExcpetion to do this?
I wouldn't use the try/catch to perform a user logic, this is wrong from a programming point of view and also not efficient.
What I would do is to check if the file exists, and n that case skip the copy operation or do whatever you want
for(Path f:files)
{
//here use Files.exists(Path path, LinkOption... options)
Files.copy(f, to.resolve(f.getFileName()));
System.out.println(" "+f.getFileName()+" copied ");
}
Here the Files docs:
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
Good luck

How can I compile code that uses a .jar file class with BlueJ?

I am learning java with BlueJ, and recently I was given a .jar file called Imagen.jar. Apparently, what it does is return some pixel vectors depending on image file names given as parameters to it.
Anyway, I am supposed to make a program that will use a class called Imagen. Apparently, such class is within the mentioned .jar file.
Clearly, BlueJ won't compile if I'm using such class since I have not imported it or anything. But, I don't really know how to import such class in the first place.
I was given the following example code:
import java.io.PrintWriter;
public class Main {
public static void main(String arg[ ]){
if(arg.length > 1){
Imagen imagen = new Imagen(arg[0]);
int [][] m = imagen.getMatriz();
PrintWriter salida = null;
try {
salida = new PrintWriter(arg[1]);
}
catch(Exception e){
System.err.println(e);
}
for(int [] fila : m ){
for(int valor : fila){
System.out.print("\t"+valor);
salida.print("\t"+valor);
}
salida.println("");
System.out.println("");
}
if(salida!=null){
salida.close();
}
}
else {
System.out.println("Uso: java -classpath .;Imagen.jar Main nombreArchivo.gif");
}
}
}
Which does not compile using BlueJ. However, as you can see, at the end it says that to use it, you have to type in the terminal:
java -classpath .;Imagen.jar Main myImageFile.gif
And I do it. But it keeps throwing me the same message.
So I am stuck right now:
Why is the terminal line I was told to use not working?
How can I import the class that is contained within a .jar file?
You need to do the following once.
Select the menu option Tools -> Preferences.
In the resulting dialog, click on the Libraries tab.
Click the Add button.
Navigate to the folder containing jar file. Select jar file.
Restart BlueJ.
Answer extracted from this place
you need to import Imagen class as it is being used in the main method.

FFMPEG in Java (runtime error)

I want to write a program that converts video into frames using FFMPEG. When I use it on the Ubuntu terminal, it works fine. But when I try to put it into the Java code, it gives me a runtime error. Did I make a mistake in my code below?
import java.util.*;
import java.awt.*;
import java.lang.*;
import java.lang.Runtime;
import java.io.*;
import java.io.IOException;
public class ConvertVideoToImage
{
private SingletonServer ss = null;
public ConvertVideoToImage(SingletonServer ss)
{
this.ss = ss;
}
public void run()
{
convertVideo();
}
public void convertVideo()
{
try
{
Runtime rt = Runtime.getRunTime().exec("ffmpeg" + "-i" + "display.wmv" + "image%d.jpg");
}
catch(Exception e){}
}
}
Edit:
I have changed the code like you suggested, but it also doesn't work. And when I Googled it, I found out that someone put the full path inside the executable and it became like this:
Runtime.getRuntime().exec("/home/pc3/Documents/ffmpeg_temp/ffmpeg -i display.wmv image%d.jpg")
BTW, thanks for the reply. I have another question. Is it possible to make a counter for FFMPEG? I used this command in the Ubuntu terminal to make it convert a video to 30 frames/1seconds:
ffmpeg -i display.wmv image%d.jpg
This will automatically generate numbers like image1.jpg, image2.jpg, to image901.jpg. Is it possible to make a counter for this? Because I need to count the files and control the number.
Thanks in advance.
When you call exec, you should not specify the parameters in the command string, instead, pass them in an array as second parameter.
Process p = Runtime.getRunTime().exec("ffmpeg",
new String[]{"-i", "display.wmv", "image%d.jpg"));
// are you sure regarding this %^

Categories