• 0

importing files from hard drive in java


Question

Im trying to import a file into java, which works with an example import file I found online, but I dont really know how it works. I tryed to write an import file my self but failed. I marked the lines in the code that I dont understand with numbers, so if u could please tell me what the commands mean and do to help me understand it

import java.io.*;

class FileImport2 { 

 ? //--------------------------------------------------< main >--------//

 ? public static void main (String[] args) {
 ? ?FileImport2 t = new FileImport2(); ? //1
 ? ? ?t.readMyFile(); ? ? ?//2
 ? } 


 ? //--------------------------------------------< readMyFile >--------//

 ? void readMyFile() { ? ? ? ? ? ? ? ? ? //3

 ? ? ?String record = null;
 ? ? ?int recCount = 0; 

 ? ? ?try { 

 ? ?FileReader fr ? ? = new FileReader("data.csv");
 ? ? ? ? BufferedReader br = new BufferedReader(fr); ?//4

 ? ? ? ? record = new String();
 ? ? ? ? while ((record = br.readLine()) != null) { ? 
 ? ? ? ? ? ?recCount++;
 ? ? ? ? ? ?System.out.println(recCount + ": " + record); 
 ? ? ? ? } 

 ? ? ?} catch (IOException e) { 
 ? ? ? ? System.out.println("Uh oh, got an IOException error!");
 ? ? ? ? e.printStackTrace(); ? ?//5
 ? ? ?}

 ? }

}

also, can I import files without exception handling?

thx!

EDIT: also, how would I rewrite that file so that I get an return value that I can use in another class?

Edited by eccofresh
Link to comment
Share on other sites

8 answers to this question

Recommended Posts

  • 0

1: Create an instance/object of the class FileImport

2: run readMyFile() function

3: the function which reads the file. (Note: this function is poorly designed - it has a hard coded file name)

4: you create an instance of BufferedReader to read the file

5: printStackTrace() displays stack trace leading tothe line of code that caused the exception

Link to comment
Share on other sites

  • 0
1: Create an instance/object of the class FileImport

2: run readMyFile() function

3: the function which reads the file. (Note: this function is poorly designed - it has a hard coded file name)

4: you create an instance of BufferedReader to read the file

5: printStackTrace() displays stack trace leading tothe line of code that caused the exception

when I get this to run, then I wana change it so it prompts the user which file he likes to import. How can I call the readMyFile function in a different class and convert it to a string?

Link to comment
Share on other sites

  • 0

I have coded this by memory, so there maybe a few errors.

import java.io.*;

class FileImport 
{ 
 ? private StringBuffer buffer; //global used to store what is read in from the file

/*
 * Main Method
 */ ? ?
public static void main (String[] args) 
{
 ? //get file to read/import
 ? System.out.print("Enter file to import: ");
 ?
 ?//create this object to read console input ?
 ?BufferedReader br = new BufferedReader(new InputStreamReade(System.in));
 ? 
 ?try {
 ? ? ? ? ?//read console input ? ? ? ? 
 ? ? ? ? ?String importFile = br.readLine(); 

 ? ? ? ? //create instance of file importer
 ? ? ? ? FileImport fileImport = new FileImport();

 ? ? ? ? //read the file ?
 ? ? ? ? t.readMyFile(importFile); ? ? ?

 ? ? ? ? //print file that was read in
 ? ? ? ? System.out.println(t.toString());
 ? ? ? } 
 ? ? ? ? catch (IOException e) 
 ? ? ? ? { 
 ? ? ? ? ? ?System.out.println("An error occurred:" +e.getMessage() );
            br.close(); ?
 ? ? ? ? } 


 ? 
} 

/*
 * reads a file 
 */ ? ? 
void readMyFile(String importFile) throws Exception
{ ? ? ? ? ? ? ? ? ? 
 ? ? try {

 ? ? ?//set up the file ?
 ? ? ?FileReader fileReader = new FileReader(importFile);

 ? ? //read the file using this buffer
 ? ? BufferedReader br = new BufferedReader(fileReader); 

 ? ? //read data into this global string buffer
 ? ? buffer = new StringBuffer();

 ? ? ?int linesRead =0;

 ? ? //read lines in the file until null is returned
 ? ? ?while ((String aLine = br.readLine()) != null) 
 ? ? { ? 
 ? ? ? ? ? buffer.append(aLine)
 ? ? ? ? ? linesRead++;
 ? ? } 

 ? ? System.out.println("Finished Reading File: "+linesRead+" Lines Read"); 
 ? ?} catch(Exception ex) 
 ? ? ?{
 ? ? ? ? //try and close inputs
 ? ? ? ? br.close(); 
 ? ? ? ? fileReader.close();

 ? ? ? ? //re throw the exception to be handled by main method
 ? ? ? ? throw new Exception(ex.getMessage());
 ? ? ? }
}

/*
 * converts buffer to a string 
 */ ? ? 
public String toString() 
{
 ? return buffer.toString();
} ?

}

Link to comment
Share on other sites

  • 0

thx alot liykh001. I am allready using eclipse and I think its great.

I will try your code at work tomorow and see how it works. Ive pretty much completed my own code by now aswell, my only problem is that I can read the info that gets loaded in that class, but I cant read it in a different class and I dunno why :wacko:

thats what I got so far:

the file that imports the file:

package com.ssn; 
import java.io.*; 

public class FileImport2 { 
 ? ? ? ? ?public String Record; 
 ? ? ? ?public FileImport2(String pfad) { 
 ? ? ? ? ? ? ? ?
 ? ? ? ? ? ? ? ?String sRecord = new String(); 
 ? ? ? ? ? ? ? ?int recCount = 0; 




 ? ? ? ? ? ? ? ?try { 

 ? ? ? ? ? ? ? ? ? ? ? ?FileReader fr = new FileReader("pfad"); 
 ? ? ? ? ? ? ? ? ? ? ? ?BufferedReader br = new BufferedReader(fr); 

 ? ? ? ? ? ? ? ? ? ? ? ?//sRecord = new String(); 
 ? ? ? ? ? ? ? ? ? ? ? ?while ((sRecord = br.readLine()) != null) { 
 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?recCount++; 
// ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?System.out.println(recCount + ": " + sRecord); 
 ? ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? System.out.println(recCount + ": " + sRecord); 

 ? ? ? ? ? ? ? ?} catch (IOException e) { 
 ? ? ? ? ? ? ? ? ? ? ? ?System.out.println("Uh oh, got an IOException error!"); 
 ? ? ? ? ? ? ? ? ? ? ? ?e.printStackTrace(); 
 ? ? ? ? ? ? ? ? ? ? ? ?
 ? ? ? ? ? ? ? ?} 

 ? ? ? ?} 
}

the class that actually needs the imported file:

package com.ssn; 
//import java.io.*; 
//import java.util.*; 
import javax.swing.*; 



public class ImportCsv { 
 ? ? ? ?public static void main(String[] args) { 
 ? ? ? ? ? ? ? ?String pfad = JOptionPane.showInputDialog("Wie ist der Pfad zu der Datei?"); 
 ? ? ? ? ? ? ? ?
 ? ? ? ? ? //String pfad = new String(args[0]); 
 ? ? ? ? ? ? ? ?FileImport2 test = new FileImport2(pfad); ? ? ? ?//erzeugt ein object test. ruft den FileImport2.class constuctor auf, 

 ? ? ? ? ? ? ? ?//System.out.print(test.sRecord); 
 ? ? ? ? ? ? ? ?String str = test.Record; 
 ? ? ? ? ? ? ? ?System.out.print(str); 
 ? ? ? ? ? ? ? ?System.exit( 0 ); 

//Some { are:)issing since I didnt copy the complete code...

I also changed my imput away from the static file, but Im using the JOptionPane thingy so the user gets a nice little pretty to look at graphical non text userfriends box that all users love so much... :)

Link to comment
Share on other sites

  • 0
but I cant read it in a different class and I dunno why

I dont either, I am actually not sure what you mean by cant read it in a different class?

- are you getting any error messages?

Hint: if your class has errors, try right hand mouse clicking on the File. Select Source->Organize Imports

or press Ctrl+O with the file open and selected

This will automatically resolve class that need to be imported.

Link to comment
Share on other sites

  • 0

I fixed up the code I posted earlier - this one compiles and works

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

class FileImport 
{ 
  private StringBuffer buffer;   //global used to store what is read in from the file
  private File importFileName;   //store the file name and path that will be imported
  private final String NLINE = System.getProperty("line.separator");

/*
* Main Method
*/    
public static void main (String[] args) 
{
  

         //allow user to select a file
         JFileChooser fc = new JFileChooser();
         fc.setDialogTitle("Please Select Import File?");
         fc.showOpenDialog(null);

         //create instance of file importer
         FileImport fileImport = new FileImport(fc.getSelectedFile());
         
         try 
         { 
           //read the file  
           fileImport.readImportFile();      

           //show text file that was read in
           
           //create a text area and put text in it
           JTextArea textArea = new JTextArea(fileImport.toString());
           textArea.setSize(300,300);
           
           //create a scrollpane to show scrollbars
           JScrollPane scrollPane= new JScrollPane(textArea);
           
           //create a frame to show the scrollpane
           JFrame frame = new JFrame("File Import Complete");
           frame.setSize(310,310);
           frame.setContentPane(scrollPane);
           frame.show();
         } 
         catch (Exception e) 
         {
           JOptionPane.showMessageDialog(null,
                                         "An error occurred:" +e.getMessage(),
                                         "File Importer",
                                         JOptionPane.ERROR_MESSAGE);  
         } 

} 
/*
* constructor
* init import filename
*/  
public FileImport(File importFileName)
{
    super();
    this.importFileName = importFileName;
}

/*
* reads a file 
*/     
void readImportFile() throws Exception
{    
    //check that a file has been selected
    if (importFileName == null)
        throw new Exception("No File Selected");
    
    //set up the file  
    FileReader fileReader = new FileReader(importFileName);
    
    //read the file using this buffer
    BufferedReader br = new BufferedReader(fileReader);
    
    //read data into this global string buffer
    buffer = new StringBuffer();
    
    try 
    { 
     int linesRead = 0;
     String aLine  = "";
     
     //read lines in the file until null is returned 
     //need to add NLINE to buffer or else text will be all on one line 
     while ((aLine = br.readLine()) != null) 
    {   
          buffer.append(aLine + NLINE);
          linesRead++;
    } 

    System.out.println("Finished Reading File: "+linesRead+" Lines Read"); 
   } catch(Exception ex) 
     {
        //try and close readers
        br.close(); 
        fileReader.close();

        //re throw the exception to be handled by main method
        throw new Exception(ex.getMessage());
      }
}

/*
* converts buffer to a string 
*/     
public String toString() 
{
  return buffer.toString();
}  
}

Link to comment
Share on other sites

  • 0

thx for your help liykh001. This made me understand the hole thing a little better and I could finish my code. what I mean by reading from a different class:

for my program I dont have all that in one class. I have two different classes, one that just reads the file and returns the file contents, and then the other class actually does something with the stuff that was in the file that I read.

your code is actually a little to much of what I need for my program, but its pretty cool.but Im gona see if I can mod the part into my code so I can browse my pc for files instead of having the crappy little text box pop up.

thx!

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.