• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to copy a .txt file to .sav file in java?  RSS feed

 
Rogerio Ribeiro
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.Scanner ;
import java.io.File ;
import java.io.PrintWriter ;
import java.io.FileNotFoundException ;

public class CopyFile
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner(new File("cat.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}

//check what is in cat.sav
scanner = new Scanner(new File("cat.sav")) ;
int count = 3 ;
for (int i = 0 ; i < count && scanner.hasNextLine(); i++) {
System.out.println(scanner.nextLine()) ;
}
}
}

The above is what I have coded but i need help to copy the "cat.txt" file to the "cat.sav" file. Could anybody help me?
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't bother with Scanner and lines, and just read the raw bytes using FileInputStream and FileOutputStream.
 
Tony Docherty
Bartender
Posts: 3268
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

Do as Ulf says, remembering to wrap the appropriate streams in a BufferedInputStream and a BufferedOutputStream.
Alternatively, if you are using Java 7 you can use the java.nio.Files.move() method to rename/move a file or the java.nio.Files.copy() method to copy it.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!