In: Computer Science
How can I fix this code to accomplish the goal of reading and writing on binary or text files?
3 import java.io.*;
4 import java.io.FileOutputStream;
5 import java.io.FileInputStream;
6 import java.util.Scanner;
7
8 public class ReadAndWrite implements Serializable
9 {
10 public static void main(String[] args)
11 {
12 boolean file = true;
13 Scanner inputStream;
14 PrintWriter outputStream;
15 FileInputStream inputBinary;
16 FileOutputStream readBinary;
17 FileInputStreamText writeText;
18 FIleOutputStreamText readText;
19 StringBuffer contents = new StringBuffer();
20 Scanner keyboard = new Scanner(System.in);
21 String yn = "Y N", fileName = " ", line = " ", tb = "T B", rw =
"R W";
22
23 while(file)
24 {
25 System.out.println("Enter the file name.");
26 fileName = keyboard.nextLine();
27 System.out.println("Choose binary or text file (b/t):");
28 tb = keyboard.nextLine();
29 if (tb.equalsIgnoreCase("b"))
30 {
31 System.out.println("Choose read or write (r/w):");
32 rw = keyboard.nextLine();
33 if (rw.equalsIgnoreCase("r"))
34 {
35 inputBinary = new PrinterWriter(new
FileInputStream(fileName));
36 System.out.println("File contains:" + readBinary);
37 inputBinary.close();
38 }
39 else
40 {
41 System.out.println("Enter a line of information to write to the
file:");
42 line = keyboard.nextLine();
43 System.out.println("Would you like to enter another line?
(y/n)");
44 yn = keyboard.nextLine();
45 if(yn.equalsIgnoreCase("n"))
46 {
47 file = false;
48 }
49 }
50 }
51 }
52
53 do
54 {
55 System.out.println("Choose read or write (r/w):");
56 rw = keyboard.nextLine();
57 if (rw.equalsIgnoreCase("r"))
58 {
59 FileInputStreamText = new Scanner(new
FileInputStream(outputStream + ".txt"));
60 String textLine = null;
61 }
62 else
63 {
64 System.out.println("Enter a line to write to the file:");
65 line = keyboard.nextLine();
66 System.out.println("Would you like to enter another line?
(y/n)");
67 yn = keyboard.nextLine();
68 if(yn.equalsIgnoreCase("n"))
69 {
70 file = false;
71 }
72 }
73 }while(tb.equalsIgnoreCase("t"));
74 System.out.println("Process completed");
75 }
76 }
This program run much faster by copying a chunk of bytes at a time
import
java.io.*;
public
class
CopyFilesChunk
{
private
static
final
int
BUFFER_SIZE =
4096
;
//
4KB
public
static
void
main(String[] args)
{
if
(args.length <
2
) {
System.out.println(
"Please
provide input and output files"
);
System.exit(
0
);
}
String
inputFile = args[
0
];
String
outputFile = args[
1
];
try
(
InputStream
inputStream =
new
FileInputStream(inputFile);
OutputStream
outputStream =
new
FileOutputStream(outputFile);
)
{
byte
[]
buffer =
new
byte
[BUFFER_SIZE];
while
(inputStream.read(buffer) != -
1
)
{
outputStream.write(buffer);
}
}
catch
(IOException ex) {
ex.printStackTrace();
}
}
}