copy contents from one file to another file(dont overwrite if exists) - java

I have written a java code to copy contents from 1 file to other. here what it is said is that if the file exists it shoudn't be over written. i have used that case so if it exists it doesn't overwrite but it erases the entire content of the second file... kindly help me with the code. i have shared the question and the code here. kindly help!!
QUESTION:
java program which take source file and destination file as input as command line arguments. It copies the source file contents to destination file. If source file does not exist, it should give appropriate message to use. If destination file does not exist, it should be created. If it exists, program should ask that, “whether you want to overwrite?(Yes/No”.
On the basis of user choice, appropriate action should be taken.
JAVA CODE:
package com.files.file_handle;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileCopy {
public static void main(String[] args) throws IOException {
Scanner s=new Scanner(System.in);
FileReader fr = null;
FileWriter fw = null;
try {
System.out.println("enter a source file which exists");
String file1=s.next();
fr = new FileReader(file1);
System.out.println("enter a destination file");
String file2=s.next();
File f2=new File(file2);
if(!f2.exists()) {
fw = new FileWriter(file2);
f2.createNewFile();
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
System.out.println("file copied successfully");
} else {
fw = new FileWriter(file2);
System.out.println("do you want to overwrite? enter 'yes' or 'no'...");
char ans = s.next().charAt(0);
if(ans=='N'||ans=='n') {
System.out.println("couldnot enter data");
} else {
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
System.out.println("file updated successfully");
}
}
} catch(IOException e) {
System.out.println("file coudn't be found");
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) { //... }
}
}

The following code works perfectly, The issue was when open the file in write mode its content will be automatically cleared.
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileCopy {
public static void main(String[] args) throws IOException {
Scanner s=new Scanner(System.in);
FileReader fr = null;
FileWriter fw = null;
try {
System.out.println("enter a source file which exists");
String file1=s.next();
fr = new FileReader(file1);
System.out.println("enter a destination file");
String file2=s.next();
File f2=new File(file2);
if(!f2.exists()) {
fw = new FileWriter(file2);
f2.createNewFile();
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
fr.close();
System.out.println("file copied successfully");
} else {
System.out.println("do you want to overwrite? enter 'yes' or 'no'...");
char ans = s.next().charAt(0);
if(ans=='N'||ans=='n') {
fr.close();
// fw.close();
System.out.println("couldnot enter data");
} else {
fw = new FileWriter(file2);
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
fr.close();
System.out.println("file updated successfully");
}
}
} catch(IOException e) {
System.out.println("file coudn't be found");
} finally {
close(fr);
close(fw);
//fw.close();
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) { //...
e.printStackTrace();
}
}
}

Related

How to use contents of a string as object name of a class constructor in Java and can I use object of a class more than one times?

I am making a program which will create files and delete files etc. but the program can only create one file and after doing that it gets terminated, so I want to use String as name of create_file class object name so I can increment the numbers(String used as name of the object) so my question is, how can I use String as object name of a class constructor?
below is the source code of the program-
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Create_File {
public static void main(String[] args) throws IOException {
try {
Selecter.select();
}
catch(Exception e) {
e.printStackTrace();
}
}
static void create() throws IOException {
String name;
System.out.println("Enter a name for your file");
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));){
name = reader.readLine();
//this block is used as try with resource statement used to overcome scanner resource leak
}
try{
//file is created with the name that user gives
File obj = new File("D:\\txtfiles\\"+name+".txt");
if(obj.createNewFile()) {
System.out.println("file successfully created with the name "+obj.getName());
}
else{
System.out.println("The file already exists");
}
}
catch(IOException e){
//here exception during file creation is caught
System.out.println("An error occurred.");
e.printStackTrace();
}
// info(name);
name = null;
// Selecter.select();
}
static void info(String name) throws IOException {
File obj = new File("D:\\txtfiles\\"+name+".txt");
String data = null;
Scanner scan = new Scanner(obj);
if(obj.exists()) {
//file properties are printed out for both newly created file and the existing file
System.out.println("File properties");
System.out.println("Name of the file = "+obj.getName());
System.out.println("Path of file = "+obj.getAbsolutePath());
System.out.println("Size of file in Kb= "+obj.length()/1024); // obj.lengeth is divided by 1024 to get the file size in Kb
System.out.println("Readable = "+obj.canRead());
System.out.println("Writable = "+obj.canWrite());
}
else {System.out.println("the file does not exist");
//this block is used as try with resource statement used to overcome scanner resource leak
while(scan.hasNextLine()) {
data = scan.nextLine();
System.out.println(data);
}
}
// Selecter.select();
}
static void delete(String name) throws IOException {
try{
File obj = new File("D:\\txtfiles\\"+name+".txt");
obj.delete();
if(obj.exists()==false) {
System.out.println("file deleted successfully");
}
else {
System.out.println("file does not exist");
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
below is the source code of Selecter class-
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Selecter {
static void select() throws IOException {
String num=null;
Create_File create =new Create_File();
System.out.println("Select Action");
System.out.println("1. Create new text file");
System.out.println("2. Delete an existing file");
System.out.println("3. Find info of a file");
System.out.println("4. Print the contents of a file");
System.out.println("5. EXIT");
System.out.println("Your choice = ");
try
(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));){
int choice = Integer.parseInt(num= reader.readLine());
if(choice==1) {
create.create();
}
else if(choice == 2){
System.out.println("enter file name to delete");
String name=reader.readLine();
create.delete(name);
}
else if(choice == 3) {
System.out.println("enter file name to find its info");
String name= reader.readLine();
create.info(name);
}
else if(choice ==4) {
Buffer contents = new Buffer();
Buffer.main(null);
}
else if(choice == 5) {
System.exit(0);
}
}
// select();
}
}
or is there an alternative solution for this problem I want the program to keep running till the user wants to exit.

Why does .write not add the ints into the file? Java

I had a question regarding the File.io library. So in a class I had an assignment The Class Assignment
And I got stuck writing the part of the assignment where I need to add the ints into the output file. Here is my code right here,
import java.io.*;
import java.util.Scanner;
public class JH1_00668860 {
public static void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null)
scan.close();
}
}// end of prin
public static void process(String inputFilename) {
String fileoutputname = null;
FileInputStream file = null;
Scanner scan = null;
FileOutputStream outputFilename = null;
OutputStream ps = null;
try {
file = new FileInputStream(inputFilename);
scan = new Scanner(file);
fileoutputname = scan.next();
System.out.println(fileoutputname + "asfasdfasdfasdf");
outputFilename = new FileOutputStream(fileoutputname);
ps = new FileOutputStream(fileoutputname);
if (scan.hasNextInt() && scan.nextInt() >= 0) {
System.out.println(scan.nextInt() + "asfs");
ps.write(scan.nextInt());
} else {
System.out.println("You have ran out of data or you have a bad value");
}
System.out.println("A file was created");
} catch (FileNotFoundException e) {
System.out.println("You ran into an exception :" + e);
} catch(IOException e) {
System.out.println("You ran into an exception :" + e);
} finally {
try {
if (file != null) {
file.close();
}
if (outputFilename != null) {
outputFilename.close();
}
if (ps != null) {
ps.close();
}
// FileInputStream st = new FileInputStream(fileoutputname);
// int contents = st.read();
// while (scan.hasNextInt()) {
// System.out.print(contents);
// }
if (scan != null) {
scan.close();
}
printToScreen(fileoutputname);
} catch (IOException e) {
System.out.println("there was an exception");
}
}
}
public static void main(String args[]) {
process("file2.txt");
}
}
When I run it the console shows This
And then I go to the file on my computer named niceJob.txt which is starting as an empty file, Eclipse then says it is going to be changed, but then when i "reload" nothing shows up.
Can anyone help me debug this bug(or if it is some other thing that is happening?) Any help would be appreciated. Thanks
After your code ps.write(scan.nextInt()); try to put ps.write.flush(); or ps.flush();
EDIT:
If it still doesn't work add imports:
import java.io.BufferedWriter;
import java.io.FileWriter;
and change ps.write(scan.nextInt()); to
BufferedWriter writer = new BufferedWriter(new FileWriter(inputFilename));
writer.write(Integer.toString(scan.nextInt));
writer.newLine();
writer.flush();

Printing a string to a file in all uppercase, lowercase and reverse java

I need to input a line of text into the code and have it print that text to the file in all upper came, all lower case, and reverse. I know how to do this with string, but cannot figure out how to get it to print to the file this way. I do not need help with getting the text to print in the output but getting it to print all these ways to the actual PrintToFile.txt without actually inputting it all those different ways.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PrintToFile { //open class
private static Formatter output;
public static void main (String args[]) throws IOException { //open main
openFile();
addRecords();
closeFile();
BufferedReader printFile = new BufferedReader(new FileReader("YoastReginaITM251Project9.txt"));
for (String line; (line = printFile.readLine()) != null;) { //open for
System.out.println("Text: " + line);
System.out.println("Text in Upper Case: " + line.toUpperCase());
System.out.println("Text in Lower Case: " + line.toLowerCase());
System.out.println("Text in Reverse Case: " + line);
} //close for
} //close main
public static void openFile() { //open openFile
try { //open try
output = new Formatter("PrintToFile.txt"); //open file
} //close try
catch (SecurityException securityException) { //open catch
System.err.println("Write permission denied. Terminating.");
System.exit(1);
} //close catch
catch (FileNotFoundException fileNotFoundException) { //open catch
System.err.println("Error opening file. Terminating.");
System.exit(1);
} //close catch
} //close openFile
public static void addRecords() { //open addRecords
try { //open try
output.format("%s", input.nextLine());
} //close try
catch (FormatterClosedException formatterClosedException) { //open catch
System.err.println("Error writing to file. Terminating.");
} //close catch
catch (NoSuchElementException elementExpcetion) { //open catch
System.err.println("Invalid input. Please try again.");
input.nextLine();
} //close catch
} //close AddRecords
public static void closeFile() { //open closeFile
if (output != null)
output.close();
} //close closeFile
} //close class
String input = "MagicString";
String upperCase = input.toUpperCase();
String lowerCase = input.toLowerCase();
StringBuilder sb = new StringBuilder();
sb.append(input);
String reversedString = sb.reverse().toString();
You can use the StringBuilder class (https://docs.oracle.com/javase/tutorial/java/data/buffers.html) to create new strings as you like, then print those to file.
The simple way is:
Read from a file into a string.
Apply toUpperCase() and store it into another string.
Apply toLowerCase() and store it into another string.
Apply reverse()[own created method] and store it into another string.
Then write all these strings into the destination file.
Here is the code by which you can perform the required operation.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileRW {
public static void main(String[] args) throws FileNotFoundException, IOException {
String filename="filename.txt";
String upper,lower,reverse,line;
upper=null;
lower=null;
reverse=null;
line=null;
FileReader fileReader=new FileReader(filename);
BufferedReader bufferedReader=new BufferedReader(fileReader);
while((line=bufferedReader.readLine())!=null)
{
upper=line.toUpperCase();
lower=line.toLowerCase();
reverse=reverse(line);
writeToFile(upper,lower,reverse);
}
}
static String reverse(String test)
{ String returnString="";
int len=test.length();
for(int i=len-1;i>=0;i--)
{
returnString+=test.charAt(i);
}
return returnString;
}
static void writeToFile(String line1,String line2,String line3) throws IOException
{
String filename="content.txt";
File file =new File(filename);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(line1);
bufferWritter.write(line3);
bufferWritter.write(line2);
bufferWritter.close();
System.out.println("Done");
}
}
Maybe you could use the Scanner and FileWriter classes as well. You can try something like this if it works for your purposes:
import java.io.*;
import java.util.*;
public class Solution{
/*
* Print a string to the output file
*/
private void print(String s, FileWriter o) {
try {
o.write(s + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* Convert the strings to uppercase,
* lowercase and reverse.
*/
private void solver(Scanner sc, FileWriter o){
while(sc.hasNextLine()) {
String s = sc.nextLine();
print(s.toUpperCase(), o);
print(s.toLowerCase(), o);
print(new StringBuilder(s).reverse().toString(), o);
}
}
/*
* Main method
*/
public static void main(String args[]){
File inFile = new File("input.txt");
File outFile = new File("output.txt");
try{
Scanner sc = new Scanner(inFile);
FileWriter o = new FileWriter(outFile);
Solution s = new Solution();
s.solver(sc, o);
sc.close();
o.close();
} catch(Exception e){
System.out.println(e);
}
}
}

cannot create a txt file

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
String name = null;
public String nameInitials(String sentence)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new FileOutputStream("abc.txt."));
outputStream.println(sentence);
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("abc.txt."));
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
do
{
String word = inputStream.next();
char initial = word.charAt(0);
name = initial+"."+name;
} while (inputStream.hasNext());
return name;
}
public void main(String[]args)
{
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
Write a method called nameInitials that takes one String as argument, pertaining to somebody's full name and returns a String of the name's initials. Usage example,
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials); //should print B.A.W.R.
I try to store the full name to a txt file and read the file. But I don't know why I cannot create the abc.txt file in the folder.
This can fix your error, I tested it
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
static String name = null;
public static String nameInitials(String sentence) {
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new FileOutputStream("C:\\temp\\abc.txt"));
outputStream.println(sentence);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("C:\\temp\\abc.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
do {
String word = inputStream.next();
char initial = word.charAt(0);
name = initial + "." + name;
} while (inputStream.hasNext());
return name;
}
public static void main(String[] args) {
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
the path of file not should end of .txt. just .txt
Your code is perfect it is creating the file "abc.txt." at the project level If you want to create a file named abc.txt then you must change;
new FileOutputStream("abc.txt.") to new FileOutputStream("abc.txt")
and
new FileInputStream("abc.txt.") to new FileInputStream("abc.txt")
And if you want to create the file in a particular directory then provide the full path of that directory with the file name you want to create.
for ubuntu system;
new FileOutputStream("/home/java/abc.txt")
&
new FileInputStream("/home/java/abc.txt")
and for windows system;
new FileOutputStream("C:/java/abc.txt")
&
new FileInputStream("C:/java/abc.txt")

reading in a file from computer and editing it and saving as a new file

I am trying to load in a file from my computer with all the words of the dictionary in the file.
When I load the file i put the words into an array of strings.
I then want to eliminate all words that have more than 9 letters in them.
I then want to save the words that are 9 letters or smaller into another separate text file.
When i try to open the new file it only has 9 words in it, yet my print to the screen on eclipse will print the all words of nine or less letters.
Can anyone help!
This is a program that was gave to me as part of the question.
import java.io.*;
public class FileIO{
public String[] load(String file) {
File aFile = new File(file);
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
int i = 0;
while (( line = input.readLine()) != null){
contents.append(line);
i++;
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
System.out.println("Can't find the file - are you sure the file is in this location: "+file);
ex.printStackTrace();
}
catch (IOException ex){
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
}
String[] array = contents.toString().split("\n");
for(String s: array){
s.trim();
}
return array;
}
public void save(String file, String[] array) throws FileNotFoundException, IOException {
File aFile = new File(file);
Writer output = null;
try {
output = new BufferedWriter( new FileWriter(aFile) );
for(int i=0;i<array.length;i++){
output.write( array[i] );
output.write(System.getProperty("line.separator"));
}
}
finally {
if (output != null) output.close();
}
}
}
this is the class i tried to use
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class countdown{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/Users/Sony/Documents/dict.csv"); //Reading the File as a String array from a file called dict
String[] input = new String[inputs.length]; //new String array for strings less than 9 letters
for(int i=0;i<inputs.length;i++){
if(inputs[i].length()<=9) { //if string of index i is less than 9
input[i]=inputs[i]; //add it to the new array called input
System.out.println(input[i]); //print line to check
}
}
try{
reader.save("C:/Users/Sony/Documents/dictnew.csv",input);
//this is where i save it to the new file called dictnew.
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
After reading how you want you can split rest logic remains same.
package com.srijan.playground;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FilterLengthWords {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("Sample.txt"));
bw = new BufferedWriter(new FileWriter("Output.txt"));
String tmp = null;
while((tmp=br.readLine())!=null) {
if(tmp.length()<=9) {
bw.write(tmp);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null) {
br.close();
br=null;
}
if(bw!=null){
bw.close();
bw=null;
}
}
}
}
Thanks

Categories

Resources