Results 1 to 2 of 2

Thread: Read and Write in Java

  1. #1

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Posts
    1

    Read and Write in Java

    My question is this:

    How can you write to a .txt file (or excel, doesn't really matter) in java and read from it to compare it to other variables.

    Any Ideas or examples?


    Thanks !@

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Read and Write in Java

    Welcome to the forums
    Hope this code helps
    Code:
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    
    public class FileReader
    {
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args)
        {
            DataInputStream reader = null;
            if ( args.length < 1 )
            {
                System.out.println("Usage: FileReader path");
                return;
            }
            System.out.print(readTextFile(args[0]));
        }
    
        /**
         * Read from a file into a string
         * @param filePath
         * @return
         */
        private static String readTextFile(String filePath)
        {
            BufferedReader reader = null;
            try
            {
                reader = new BufferedReader(new java.io.FileReader(filePath));
                StringBuilder builder = new StringBuilder();
                while (reader.ready())
                {
                    builder.append(reader.readLine() + "\n");
                }
                return builder.toString();
            }
            catch (FileNotFoundException ex)
            {
                Logger.getLogger(FileReader.class.getName()).log(Level.SEVERE, null, ex);
            }
            catch (IOException ex)
            {
                Logger.getLogger(FileReader.class.getName()).log(Level.SEVERE, null, ex);
            }
            finally
            {
                try
                {
                    reader.close();
                }
                catch (IOException ex)
                {
                    Logger.getLogger(FileReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            return null;
        }
    }
    Last edited by ComputerJy; Dec 4th, 2007 at 04:47 PM.
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width