Link to home
Start Free TrialLog in
Avatar of urmi123
urmi123

asked on

READ AND SAVE A FILE

Hi,
 I have to read a file from a specific directory and save the contents and directory in the same file.
My code for reading is as follows
import java.util.*;
import java.io.*;

class readIni {
  public static void main(String args[]) {
    readIni ini = new readIni();
    ini.doit();
    }

  public void doit() {
    try{
      Properties p = new Properties();
      p.load(new FileInputStream("D:\\MyFolder\\text.ini"));
      System.out.println("user");
      p.list(System.out);
      }
    catch (Exception e) {
      System.out.println(e);
      }
    }
}
But i dont want to hardcode the path can anyone suggest me a better way. pls tell me also how do i save the contents and file.

Regds
urmilla
Avatar of zzynx
zzynx
Flag of Belgium image

>> i dont want to hardcode the path
Pass it via the arguments:

     public static void main(String args[])  // <<<< args are the arguments you start the program with
Hi urmi,

You can use JFileDialog to dynamically choose the path of the file. Do you want the user to choose  the path or it has the default path?

Let me give you the URL soon.
Sorry not JFileDialog but JFileChooser....I am thinking of VB :)
Avatar of sudhakar_koundinya
sudhakar_koundinya

class readIni {
private String file;
  public static void main(String args[]) {
    readIni ini = new readIni();
     ini.setFile("prop.txt");
    ini.doit();
    }
public void setFile(String f)
{
  file=f;
}

  public void doit() {
    try{
      Properties p = new Properties();
      p.load(new FileInputStream(file));
      System.out.println("user");
      p.list(System.out);
      }
    catch (Exception e) {
      System.out.println(e);
      }
    }
}
hey, I'm giving tu two methods

1. to read contents of any file, it returns in a String data, u've to pass it full file path.

  //** this method get file path and reads it and returns the data of file as string
   public static String readFile(String thisFile)
   {
     String fileData = "";
     try
     {
       File filePath = new File(thisFile); // File object for input file.
       InputStream inStream = new FileInputStream(filePath);
       int bytesRead = 0;
       int a = 0;
       byte[] buffer = new byte[1024]; // 1k byte input buffer.
       while((bytesRead = inStream.read(buffer)) != -1) // Read until EOF.
       {
         //System.out.println("Read " + bytesRead + " bytes.");
         a = a + bytesRead;
       }
       //System.out.println("a = " + a);
       byte buff[] = new byte[a];
       InputStream fileIn = new FileInputStream(filePath);
       int i = fileIn.read(buff);
       fileData = new String(buff);
       filePath = null;
     }
     catch(FileNotFoundException e)
     {
     }
     catch(IOException e)
     {
     }
     return fileData;
   } //** end of method



2. to write data to file. by giving file path and fileData.

  //** this method saves text data to file
   public static void saveToFile(String fileNamePath, String data)
   {
     StringBuffer thisData = new StringBuffer(data);
     //System.out.println(fileNamePath);
     //System.out.println(data);

     try
     {
       FileOutputStream outputFile = new FileOutputStream(fileNamePath); // stores an output stream reference
       FileChannel outChannel = outputFile.getChannel(); // Channel for file stream
       try
       {
         //** finally write the buffered bytes to the file using file channel
          outChannel.write(ByteBuffer.wrap(thisData.toString().getBytes("UTF-8")));
       }

       catch(IOException ex1)
       {
         //ex1.getMessage();
       }
     }
     catch(FileNotFoundException ex)
     {
       //ex.getMessage();
     }

   } //** end of method

//Naeem Shehzad Ghuman
class readIni {
private String file;
      Properties p = new Properties();
  public static void main(String args[]) {
    readIni ini = new readIni();
     ini.setFile("prop.txt");
    ini.doit();
    ini.saveIt();  
    }
public void setFile(String f)
{
  file=f;
}

  public void doit() {
    try{

      p.load(new FileInputStream(file));
      System.out.println("user");
      p.list(System.out);
      }
    catch (Exception e) {
      System.out.println(e);
      }
    }
public void saveIt()
{
 try {
               properties.setProperty("a.b", "new value");
        properties.store(new FileOutputStream(file), null);
    } catch (IOException e) {
    }
}

}
>>   properties.setProperty("a.b", "new value");
>>       properties.store(new FileOutputStream(file), null);

should be
   p.setProperty("a.b", "new value");
   p.store(new FileOutputStream(file), null);
and how to write to file.

import java.io.*;

public class TestNodeStreams {
      public static void main(String[] args) {
            try {
                  FileReader input = new FileReader(args[0]);
                  FileWriter output = new FileWriter(args[1]);
                  char[] buffer = new char[128];
                  int charsRead;

                  // read the first buffer
                  charsRead = input.read(buffer);

                  while ( charsRead != -1 ) {
                        // write the buffer out to the output file
                        output.write(buffer, 0, charsRead);

                        // read the next buffer
                        charsRead = input.read(buffer);
                  }

                  input.close();
                  output.close();
            }
            catch (IOException e) {
                  e.printStackTrace();
            }
      }
}



import java.io.*;

public class TestBufferedStreams {
      public static void main(String[] args) {
            try {
                  FileReader input = new FileReader(args[0]);
                  BufferedReader bufInput = new BufferedReader(input);
                  FileWriter output = new FileWriter(args[1]);
                  BufferedWriter bufOutput = new BufferedWriter(output);
                  String line;

                  // read the first line
                  line = bufInput.readLine();

                  while ( line != null ) {
                        // write the line out to the output file
                        bufOutput.write(line, 0, line.length());
                        bufOutput.newLine();

                        // read the next line
                        line = bufInput.readLine();
                  }

                  bufInput.close();
                  bufOutput.close();
            }
            catch (IOException e) {
                  e.printStackTrace();
            }
      }
}
Avatar of urmi123

ASKER

Hi,
 I meant i dont want to harcode the path as  p.load(new FileInputStream("D:\\MyFolder\\text.ini"));
I just want to remove D:\\MyFolder\\text. My code should automatically pick up the text.ini from the directory where it exists.
Something like this
..\\..\\text.ini.

Regds
urmilla
>> My code should automatically pick up the text.ini from the directory where it exists
So, should it search for a "text.ini" file?
>> meant i dont want to harcode the path as  p.load(new FileInputStream("D:\\MyFolder\\text.ini"));

See my last but one comment
Avatar of urmi123

ASKER

Yes it should search for text.ini which is always present  in the same folder but the folder can be on any drive.
is there anything as realtive path
the above example can be used to search your file with little modifications in it and use my code -(modified version of yours)
Regards
Sudhakar
>> in the same folder
Same as what? As the program?
Avatar of urmi123

ASKER

No program is in different folder and my file is in different folder
>> No program is in different folder and my file is in different folder

Urmilla,
I just confused



Can you describe more?
>> No program is in different folder and my file is in different folder
Then how should the program know in which folder the file is?
>>Yes it should search for text.ini
All over the available drives?
Avatar of urmi123

ASKER

My java file is in folder say c:\My Folder\Java\Client\*.java
My text file is in folder say C:\My Folder\Debug\*.ini

My java program should be capable of going to Debug folder and search for *.ini file in that folder.
>>My java file is in folder say c:\My Folder\Java\Client\*.java
>>My text file is in folder say C:\My Folder\Debug\*.ini
It's not because your java file is in C:\My Folder\Java\Client\
that the directory in which the program (the class file) will run
will also be c:\My Folder\Java\Client\
I think passing the path (C:\My Folder\Debug\) as an argument to your program is the way to go
If you don't want that, your program (which can be run from within whatever directory the user desires)
should really search all drives for a text.ini file. (Bad thing to do)
Urmilla,

searching the files is a bad idea. The reason is if the text.ini is also existing in some other folder and if your application finds that first then the results will be bad.

Try like this

If you know where exactly it is existing

System.setProperty("YourFile","text.ini");

System.getProperty("YourFile");

will help you
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of urmi123

ASKER

Hi,
 I appreciate the help which i got from all the experts.
I have an another problem.
I have text.ini file. In this file the part which is not required is commented by ";" i just want to remove all the comments from that file can anyone pls help with this.
Regds
urmilla
Here at EE,
1) if your question is solved we expect you to close it
2) if you have another question we expect you to post that in a new Q
Avatar of urmi123

ASKER

This question is part of my earlier question only so posted it here only
Thanks for accepting.

But,
- I feel like some split would've been more fair
- I think you'd better marked another comment as accepted answer (think about the people after you reading this Q)