• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

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
0
urmi123
Asked:
urmi123
  • 13
  • 8
  • 6
  • +2
1 Solution
 
zzynxSoftware engineerCommented:
0
 
zzynxSoftware engineerCommented:
>> 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
0
 
suprapto45Commented:
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.
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
suprapto45Commented:
Sorry not JFileDialog but JFileChooser....I am thinking of VB :)
0
 
zzynxSoftware engineerCommented:
0
 
sudhakar_koundinyaCommented:
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);
      }
    }
}
0
 
suprapto45Commented:
0
 
zzynxSoftware engineerCommented:
0
 
NaeemgCommented:
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
0
 
sudhakar_koundinyaCommented:
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) {
    }
}

}
0
 
sudhakar_koundinyaCommented:
>>   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);
0
 
suprapto45Commented:
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();
            }
      }
}
0
 
urmi123Author Commented:
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
0
 
zzynxSoftware engineerCommented:
>> My code should automatically pick up the text.ini from the directory where it exists
So, should it search for a "text.ini" file?
0
 
sudhakar_koundinyaCommented:
>> meant i dont want to harcode the path as  p.load(new FileInputStream("D:\\MyFolder\\text.ini"));

See my last but one comment
0
 
urmi123Author Commented:
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
0
 
sudhakar_koundinyaCommented:
0
 
sudhakar_koundinyaCommented:
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
0
 
zzynxSoftware engineerCommented:
>> in the same folder
Same as what? As the program?
0
 
urmi123Author Commented:
No program is in different folder and my file is in different folder
0
 
sudhakar_koundinyaCommented:
>> No program is in different folder and my file is in different folder

Urmilla,
I just confused



0
 
suprapto45Commented:
Can you describe more?
0
 
zzynxSoftware engineerCommented:
>> 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?
0
 
urmi123Author Commented:
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.
0
 
zzynxSoftware engineerCommented:
>>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\
0
 
zzynxSoftware engineerCommented:
I think passing the path (C:\My Folder\Debug\) as an argument to your program is the way to go
0
 
zzynxSoftware engineerCommented:
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)
0
 
sudhakar_koundinyaCommented:
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
0
 
zzynxSoftware engineerCommented:
>> searching the files is a bad idea.
As I said
0
 
urmi123Author Commented:
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
0
 
zzynxSoftware engineerCommented:
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
0
 
urmi123Author Commented:
This question is part of my earlier question only so posted it here only
0
 
zzynxSoftware engineerCommented:
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)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 13
  • 8
  • 6
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now