Click here to Skip to main content
15,888,008 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am new to programming and java. I have created an application to open a file an display information about that . I want to split that file too. In function with RandomAccessFile there is some problem in the passed parameter.
In function split() I want to use field fileName from function showFiles() but am not able to find away to do it. Plese help me.


Java
package com.Naushad;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.AccessController;






//class for awt
public class Main {

    private Frame myFrame;
    private Label topLabel;
    private Label message;
    private Label errorMessage;
    private Label botLabel1;
    private Label botLabel2;
    private Panel panel;
    public static String store;

    public Main(){
        makeGui();
    }

    public void makeGui(){

        myFrame = new Frame("Assignment");
        myFrame.setBackground(Color.white);
        myFrame.setSize(700,500);
        myFrame.setLayout(new GridLayout(6,1));

        //to close the window upon clicking cross button
        myFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
                System.exit(0);
            }
        });

        topLabel = new Label();
        topLabel.setAlignment(Label.CENTER);
        message = new Label();
        message.setAlignment(Label.CENTER);
        errorMessage = new Label();
        errorMessage.setAlignment(Label.CENTER);
        botLabel1 = new Label();
        botLabel1.setAlignment(Label.CENTER);
        botLabel2 = new Label();
        botLabel2.setAlignment(Label.CENTER);

        panel = new Panel();
        panel.setLayout(new FlowLayout());
        panel.setBackground(Color.white);


        myFrame.add(topLabel);
        myFrame.add(panel);
        myFrame.add(botLabel1);
        myFrame.add(botLabel2);
        myFrame.add(errorMessage);
        myFrame.add(message);

        myFrame.setVisible(true);

        topLabel.setText("Click on BROWSE button to select a file");
    }

    /**
     * This function checks the operating System type
     * @return  It returns the suitable path based on the Operating System
     */

    public static String checkOS(){
        String OS = System.getProperty("os.name").toLowerCase();
        if(OS.indexOf("win") >= 0){
            return "C:\\Users\\NAUSHAD\\Desktop\\";
        } else if(OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ){
            return "/home/";
        } else if(OS.indexOf("mac") >= 0){
            return "/home/";
        } else
            return null;
    }


    //opens dialogue and shows file details in frame
    private void showFiles() {

        Button b = new Button("BROWSE");
        myFrame.add(b);
        panel.add(b);

        FileDialog fileDialogue = new FileDialog(myFrame);

        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileDialogue.setVisible(true);

                //storing path of selected file in fileName
                String fileName = fileDialogue.getDirectory() + fileDialogue.getFile();
                store = fileName;

               // getting extension of selected file
                String extension = "";
                int i = fileName.lastIndexOf('.');
                if (i > 0) {
                    extension = fileName.substring(i+1);// to get part of string substring() is used
                }

                File file = new File(fileName);

                botLabel1.setText("You have selected the file " + fileDialogue.getFile()
                        + " from Directory :->    " + fileDialogue.getDirectory() );
                botLabel2.setText( "The length of file is "+ file.length() + "  Bytes"
                        + " ( " + (file.length()/1024) + " kB ) and the extension (type of file) is " + extension);


                errorMessage.setText("store is =  "+ getStore() );//  testing purpose

                //check for write protection
                if(file.canWrite()){
                    Path sourceFile = Paths.get(fileName);
                    Path targetFile = Paths.get(checkOS() + "copiedFile." + extension);//accepts sitable path from checkOS function

                    try {
                        Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException ex) {
                        message.setText("I/O Error when copying file. Check write protections.");
                    }


                }
              

            }
        });

    }

    public static String getStore() {
        return store;
    }

    //Main function -> to make the program work
    public static void main(String[] args) throws IOException {
        Main awt = new Main();
        awt.checkOS();  // boolean doubt. Should or not be called
        awt.showFiles();
        awt.split(awt.getStore());

    }



    public static void split(String fileName) throws IOException {
        
        RandomAccessFile raf = new RandomAccessFile(fileName, "r");
       
        long numSplits = 10; //from user input, extract it from args
        long sourceSize = raf.length();
        long bytesPerSplit = sourceSize / numSplits;
        long remainingBytes = sourceSize % numSplits;

        int maxReadBufferSize = 8 * 1024; //8KB
        for (int destIx = 1; destIx <= numSplits; destIx++) {
            BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(checkOS() + "split." + destIx));//getting path by checkos()
            if (bytesPerSplit > maxReadBufferSize) {
                long numReads = bytesPerSplit / maxReadBufferSize;
                long numRemainingRead = bytesPerSplit % maxReadBufferSize;
                for (int i = 0; i < numReads; i++) {
                    readWrite(raf, bw, maxReadBufferSize);
                }
                if (numRemainingRead > 0) {
                    readWrite(raf, bw, numRemainingRead);
                }
            } else {
                readWrite(raf, bw, bytesPerSplit);
            }
            bw.close();
        }
        if (remainingBytes > 0)

        {
            BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(checkOS() + "split." + (numSplits + 1)));
            readWrite(raf, bw, remainingBytes);
            bw.close();
        }
        raf.close();

    }
    public static void readWrite(RandomAccessFile raf, BufferedOutputStream bw, long numBytes) throws IOException {
        byte[] buf = new byte[(int) numBytes];
        int val = raf.read(buf);
        if (val != -1) {
            bw.write(buf);
        }
    }
}


What I have tried:

I tried storing value of fileName in store field. and also used function to get value of fileName. But am not able to use it.
Posted
Updated 18-Mar-18 6:20am
Comments
Richard MacCutchan 16-Mar-18 9:54am    
Probably because you have declared split as static, so it does not have access to the current object's variables.

1 solution

Calling the split function from the showfiles function made it work
 
Share this answer
 
Comments
Patrice T 18-Mar-18 13:22pm    
If it solve your problem, Accept your solution to close the question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900