Question

In: Computer Science

How can I fix this code to accomplish the goal of reading and writing on binary...

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 }

Solutions

Expert Solution

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();

        }

    }

}


Related Solutions

Hello I have this error in the code, I do not know how to fix it....
Hello I have this error in the code, I do not know how to fix it. It is written in C++ using a Eclipse IDE Error: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string bus.h =========== #pragma once #include using namespace std; class Bus { private:    string BusId; // bus ID    string Manufacturer; // manufacturer of the bus    int BusCapacity; // bus capacity    int Mileage; // mileage of bus    char Status; // current status...
How do I fix the "error: bad operand types for binary operator '*' " in my...
How do I fix the "error: bad operand types for binary operator '*' " in my code? What I am trying to do: double TotalPrice = TicketPrice * NoOfTickets;       My code: import javax.swing.*; /*provides interfaces and classes for different events by AWT components*/ import java.awt.event.*; import javax.swing.JOptionPane; //TicketReservation.java class TicketReservation { public static void main(String args[]) { /*Declare JFrame for place controls.*/ JFrame f= new JFrame("Movie Ticket Reservation");                                   /*Declare JLabels*/ JLabel...
I already have the code of this program, I just want to know how to fix...
I already have the code of this program, I just want to know how to fix the code to Implement the 5th function (System.nanotime() and System.currentTimeMillis() methods) What Code does: Introduction Searching is a fundamental operation of computer applications and can be performed using either the inefficient linear search algorithm with a time complexity of O (n) or by using the more efficient binary search algorithm with a time complexity of O (log n). Task Requirements In this lab, you...
Python 3 Fix the code so i can make the window larger or smaller and the...
Python 3 Fix the code so i can make the window larger or smaller and the fields adjusts everytime according to the window size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window)...
I wrote this code and it produces a typeError, so please can you fix it? import...
I wrote this code and it produces a typeError, so please can you fix it? import random def first_to_a_word(): print("###### First to a Word ######") print("Instructions:") print("You will take turns choosing letters one at a time until a word is formed.") print("After each letter is chosen you will have a chance to confirm whether or not a word has been formed.") print("When a word is formed, the player who played the last letter wins!") print("One of you has been chosen...
Can you fix to me this code plz I just want to print this method as...
Can you fix to me this code plz I just want to print this method as the reverse. the problem is not printing reverse. public void printBackward() {               Node curr = head;        Node prev = null;        Node next = null;               System.out.print("\nthe backward of the linkedlist is: ");               while(curr != null) {            next = curr.next;            curr.next = prev;   ...
I'm getting an error message with this code and I don't know how to fix it...
I'm getting an error message with this code and I don't know how to fix it The ones highlighted give me error message both having to deal Scanner input string being converted to an int. I tried changing the input variable to inputText because the user will input a number and not a character or any words. So what can I do to deal with this import java.util.Scanner; public class Project4 { /** * @param args the command line arguments...
Why is this java code reaching a deadlock and how to I fix it without serializing...
Why is this java code reaching a deadlock and how to I fix it without serializing the code (i.e. I don't want to do not have the Girl authenticate the Boy then have the Boy authenticate the Girl)? import java.applet.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; // Attempt at a simple handshake. Girl pings Boy, gets confirmation. // Then Boy pings girl, get confirmation. class Monitor { String name; public Monitor (String name) { this.name = name; } public String...
Python 3 Fix the code so i can make the window larger and the fields increase...
Python 3 Fix the code so i can make the window larger and the fields increase size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window) #...
Python 3 Fix the code so i can make the window larger and the fields increase...
Python 3 Fix the code so i can make the window larger and the fields increase size Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT