Solved

READ AND SAVE A FILE

Posted on 2004-10-12
33
227 Views
Last Modified: 2010-03-31
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
Comment
Question by:urmi123
  • 13
  • 8
  • 6
  • +2
33 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 12284672
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12284681
>> 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
 
LVL 16

Expert Comment

by:suprapto45
ID: 12284684
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 12284691
Sorry not JFileDialog but JFileChooser....I am thinking of VB :)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12284694
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12284698
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 12284700
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12284703
0
 
LVL 5

Expert Comment

by:Naeemg
ID: 12284729
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12284749
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12284755
>>   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
 
LVL 16

Expert Comment

by:suprapto45
ID: 12284768
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
 

Author Comment

by:urmi123
ID: 12284773
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12284805
>> 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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12284822
>> meant i dont want to harcode the path as  p.load(new FileInputStream("D:\\MyFolder\\text.ini"));

See my last but one comment
0
 

Author Comment

by:urmi123
ID: 12284847
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12284872
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12284883
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12284887
>> in the same folder
Same as what? As the program?
0
 

Author Comment

by:urmi123
ID: 12284959
No program is in different folder and my file is in different folder
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12284973
>> No program is in different folder and my file is in different folder

Urmilla,
I just confused



0
 
LVL 16

Expert Comment

by:suprapto45
ID: 12285071
Can you describe more?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12285110
>> 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
 

Author Comment

by:urmi123
ID: 12285176
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12285190
>>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
 
LVL 37

Expert Comment

by:zzynx
ID: 12285200
I think passing the path (C:\My Folder\Debug\) as an argument to your program is the way to go
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12285208
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12285246
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
 
LVL 37

Accepted Solution

by:
zzynx earned 500 total points
ID: 12285270
>> searching the files is a bad idea.
As I said
0
 

Author Comment

by:urmi123
ID: 12336324
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12336574
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
 

Author Comment

by:urmi123
ID: 12336587
This question is part of my earlier question only so posted it here only
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12368448
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

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now