How to store a data on txt file through java program

that means i want a coding for write data on txt file using java program.that storing data is stored like this formate,
sathees
krishnan
rama
suresh
Stored on one by one. not like this
sathees krishnan rama suresh.........

import java.io.*;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class rsk1{
public static void main (String argv []){
try {
String sr[] = new String[100];
               String s1=" ";
               int j=0;
               DataInputStream in = new DataInputStream(System.in);
               OutputStream f1 = new FileOutputStream("file1.txt");
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);
for(int s=0; s<listOfPersons.getLength() ; s++){
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
sr[++j]=((Node)textFNList.item(0)).getNodeValue().trim();
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
sr[++j]=((Node)textLNList.item(0)).getNodeValue().trim();
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
sr[++j]=((Node)textAgeList.item(0)).getNodeValue().trim();
NodeList stuList = firstPersonElement.getElementsByTagName("stu");
Element stuElement = (Element)stuList.item(0);
NodeList textstuList = stuElement.getChildNodes();
sr[++j]=((Node)textstuList.item(0)).getNodeValue().trim();
}//end of if clause
}//end of for loop with s var
System.out.println("Process completed");
for(int i=1;i<=j;i++)
               byte buf[] = sr.getBytes();
                                   byte buf1[] = s1.getBytes();
     f1.write(buf);
                                   f1.write(buf1);
f1.close();
}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
}//end of main

Similar Messages

  • How to store the data of a file into an ArrayList?

    Hi! everyone.
    I want to know
    if I have a File, and the data in the file are type int, type String...
    And I have a ArrayList which is of type Question
    How do I store the data of that file into the ArrayList
    I tried to use the while loop(use the hasNextLine() to read the data line by line)
    But I cannot add data which are not of type Question to the ArrayList.
    Can you tell me what I should do, please?
    I also wonder that
    The data of the file are of many types, but when I try to read it with the nextLine(), the data all turn out to be of type String. Why?
    Thank you.
    Edited by: Terry001 on Apr 30, 2008 1:13 PM

    No, a line in the file is just part of a question
    The format of the file is like this:
    *<question type code>                    :     String*
    *<question point value>                    :     int*
    *<question category>                         :     String*
    *<question difficulty level>               :     int*
    *<question text>                              :     String*
    *<question correct answer>               :     String*
    *<optional question-specific data>     :     String*
    *<question terminator>                    :     String*
    And here is an example
    TF //TrueFalseQuestion
    5 //points value
    None //category
    3 //difficulty level
    The capital of the United States is Washington, D.C. //question text
    True // answer
    *** //quetion terminator
    I created an ArrayList in the Test class:
    private ArrayList<Question> questions; // Create inside constructor
        public Test (String name, String instr)
            testName = name;
            scoreEarned = 0;
            scorePossible = 0;
            instructions = instr;
            questions = new ArrayList<Question>(); //[MAX_NUMBER_OF_QUESTIONS];
        }And I tried to use the following method to store the data of the file to the ArrayList
    // This method loads a set of questions from a plain text file
        public void loadQuestionsFromFile(String fileName) throws FileNotFoundException
            try
                File fileReader = new File("input.txt");
                Scanner sc = new Scanner(fileReader);
                while (sc.hasNextLine())
                    // I don't know how to pass the data I got from the nextLine() method to the ArrayList because they are of different type
            catch (FileNotFoundException a)
                System.out.println(a);
        }    As all you said, I should create an Question object in the while loop
    Question temp = new Question ();But I have no idea how to pass the int and String to the Question object.
    Thank you

  • How to compile dunamically genrated java files through java program?

    Hi, I have a requirement where i generate java files from WSDL dynamically using wsdl2java jaxbri. I need to compile these files dynamically on the fly and jar it. Everything should happen through java program. Bcos everything is dynamic here, no information is known (like dir, file names ...) until the runtime. Everything is user fed.
    the directories may contain other directories with java files. its recursive
    i tried com.sun.tools.javac.Main.. but either its not scaling to my needs or i donno how to wok with this.
    is there any option to compile the java files as they are created thru JAXBRI (wsdl2java)?
    any help is appreciated..
    -s

    my requirement is :
    i create java files from wsdl2java (axis).. i need to compile all the java files.. directories with in the directories (recursive)...
    as bcos the the java files have inter-dependencies they have to be compiled as a bunch something like (java *.java). I donno how to do this in javac.Main tool
    Once all these files are compiled i need to create a jar out of them
    Any help is appreciated!

  • Updation in zip file through java program

    Hi,
    Can any buddy help me updating zip file using java programs. I dont want to delete the zip file but I want to update single file in the zip.
    Any clue ?
    Regards,
    Ashish

    I mean I want to update a zip file using java program.
    Suppose there are 4 files zipped into single zip file.
    zipped.zip contains a.txt, b.txt. c.txt. d.txt
    Now the contect of a.txt got changed and I want to update zipped.zip to with the changed a.txt.
    I have one way of creating a new file with new set of a.txt, b.txt, c.txt and then delete the earliar zipped.zip and rename the newly created zipped to zipped.zip.
    I dont want to do the same as above mentioned way. Is there any way provided in java API to remove any entry or update any entry?
    I feel now the problem has got explained in details.
    Any help ?

  • Writing into a jar file through Java program

    Is there a way to get a file from a jar (for ex. a properties file) make changes to it on the fly and write the same file back to the jar through a Java program?

    I cannnot give u exact code as i am bit busy..but i am giving close to exact
    below is code for reading contents of jar file
    import java.io.*;
    import java.util.jar.*;
    public class JarRead {
    public static void main (String args[])
    throws IOException {
    if (args.length != 2) {
    System.out.println(
    "Please provide a JAR filename and file to read");
    System.exit(-1);
    JarFile jarFile = new JarFile(args[0]);
    JarEntry entry = jarFile.getJarEntry(args[1]);
    InputStream input = jarFile.getInputStream(entry);
    process(input);
    jarFile.close();
    private static void process(InputStream input)
    throws IOException {
    InputStreamReader isr =
    new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(isr);
    String line;
    while ((line = reader.readLine()) != null) {
    System.out.println(line);
    reader.close();
    now here say u have test.jar which contains test.txt (file)
    then
    java JarRead test.jar test.txt
    will print content of text.txt
    now in ur case u write content of each file in some other file modify it there and then create a jar file from those files using jaroutput stream .....
    this may not be all clear ..but what to do..bit busy...u are welcomed to make changes in above stratergy....n queries if any after using above stratergy and/or your great brain...

  • How to store context data in XML file in Webdynpro

    Hi all
    i have one typical requirement as follows.
    1) i want to store context data of one view  in XML file and i want to read the same data from XML into another context of View.
    is there any one did this functionality then it is great help to me if they share?
    Thanks
    Sunil

    Hi,
    In WD4A
    Check out the mehtod in IF_WD_CONTEXT_NODE-
    TO_XML returns the string about the context.
    Regards
    Lekha

  • How to store grid points in a file using Java Swing?

    Please someone help me with any suggestions about how to store the grid points in a file using Java Swing

    Actually i have designed a gridlayout in Java Swing and have added some components to it such as buttons or images....My problem is when I click on any of the cell of the grid,the corresponding cell number should be stored in an external file....Do u have any suggestions on how to do it?

  • How to compare and edit Resource bundle file using java programe

    Hi All
    I have two resource bundle with key, value and some comments. I need to write a java code to compare both of the values of the keys and if the values are different then i want to replace the second value with the first value.
    Its a programe which will udpate the second file with the first file values.
    I tried using Properties class but it didnt worked because when i am saving the file using store method it removes all the comments and the order of text also got disturbed.
    How I need to do this any help appriciated.
    Please elt me know if someone needs more info.
    Thanks in advance.

    Let's assume the ini file is a mapping type storage (key=value) so lets use Properties object. (works with java 1.4 & up)
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Properties;
    public class Test {
         private static Properties props;
         public static void main(String[] args) throws IOException {
              File file = new File("test.ini");//This is out ini file
              props = new Properties();//Create the properties object
              read(file);//Read the ini file
              //Once we've populated the Properties object. set/add a property using the setProperty() method.
              props.setProperty("testing", "value");
              write(file);//Write to ini file
         public static void read(File file) throws IOException {
              FileInputStream fis = new FileInputStream(file);//Create a FileInputStream
              props.load(fis);//load the ini to the Properties file
              fis.close();//close
         public static void write(File file) throws IOException {
              FileOutputStream fos = new FileOutputStream(file);//Create a FileOutputStream
              props.store(fos, "");//write the Properties object values to our ini file
              fos.close();//close
    }

  • How to call a exe or bat file from java program

    hi,
    i actually want to know that how to call a exe or bat file from program so that i can run them parallely.

    Try this :
    String strCmd = "myFile.bat";
    try
         Runtime rTime = Runtime.getRuntime();
         Process process = rTime.exec(strCmd);
         InputStream p_in = process.getInputStream();
         OutputStream p_out = process.getOutputStream();
         InputStream p_err = process.getErrorStream();
         p_in.close();
         p_out.close();
         p_err.close();
    catch(Exception e) {
         throw new Exception("Unable to start, "+strCmd);
    }

  • Please help how to run System commands and batch files thru java program

    Sir,
    I want execute OS commands like dir,cls..etc and batch files,.exe filesthru java program.
    I have tried it sofar thru Runtime.getRuntime().exec("execute.bat");
    but it is not working.anybody knows about how to run the system commands thru java please give me the code.
    thank you,
    regards,
    j.mouli

    I've seen other posts with this questions, and answers. Unfortunately I didn't pay much attention. But the basic idea is to exec command.com and pass the specifc batch or command as an argument.

  • Invoking exe file through java program

    I have one exe file,which i want to invoke it from java program.I have used Runtime class to execute the exe, but it throws an exception
    java.io.IOException: CreateProcess: afp2web.exe -q -PDF -c -fm samples\medform.a
    fp error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at Afp2PdfDemo.main(Afp2PdfDemo.java:7)
    However if i give the absolute path of exe file then it doesn't throw an exception but at the same time,it doesn't the do the expected job.
    Can somebody throw some light on this?
    Thanx in advance
    Regards,
    Pulak

    Have you tried also supplying the absolute paths of the file arguments like "samples\medform.a"?

  • How to store my data in a file?

    I Get my data in several indicators. I need to store them in a file

    Pushpa,
    You should use VIs from the File I/O palette to save the data to your hard disk.
    You can also look into /examples/file VIs for additional help on how to save to different file types.
    In the feature, you should post the pure LabVIEW related questions to the LabVIEW forum.
    Zvezdana S.

  • How to open and store a data to excel file usig java

    you hava a data in database .you can reterive the data and tranformed to excel file.you can save as well as poen it possible or not?

    Here is your basic issue: setting a classpath (and presumably compiling and executing a program) is one of the most basic, fundamental concepts in Java. I would advise you to follow JVerd and Annie's links and get started on a tutorial. Try writing a simple HelloWorld application before delving into POI. When you are more comfortable writing and compiling programs, and post a specific question, it will be much easier to help you.
    - Saish

  • How to store the data read from excel using java code in Ms access database

    Hi. I wrote a code to read the data from excel. May i know how can i save it to Ms access database using java. Also i have many excels. So i should not connect the database using DSN. So is there any other way to achieve this?

    kramish wrote:
    Im pretty sure that Access does support JDBCNo it does not. It supports ODBC.
    just doing a quick Google came up with some pages:
    http://blog.taragana.com/index.php/archive/access-microsoft-access-database-from-java-using-jdbc-odbc-bridge-sample-code/
    http://www.javaworld.com/javaworld/javaqa/2000-09/03-qa-0922-access.html
    Both articles explains how to use the jdbc-odbc bridge. I think I've seen a pure jdbc driver for access but it wasn't from Microsoft and it wasn't free.
    Kaj

  • How to call function in included dll file through java application.

    Hi All,
    i am trying to create an java application which call c# functions using JNI. i am completed with the code and it is running fine when i tried to run from netbeans IDE. But when i tried from Calculator.jar file, first time it throws this error:
    F:\JavaProjects\Calculator\dist>Java -jar Calculator.jar
    Exception in thread "main" java.lang.UnsatisfiedLinkError: no CSharpClient in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at calculator.CalculatorApp.<clinit>(CalculatorApp.java:20)
    After that i included that dll file in the cuurent directory. And compiled and tried to run, it throws an unexpected error:
    F:\JavaProjects\Calculator\dist>Java -jar Calculator.jar
    *# An unexpected error has been detected by Java Runtime Environment:*
    *# Internal Error (0xe0434f4d), pid=2640, tid=3700*
    *# Java VM: Java HotSpot(TM) Client VM (1.6.0_02-b06 mixed mode, sharing)*
    *# Problematic frame:*
    *# C [kernel32.dll+0x12a5b]*
    *# An error report file with more information is saved as hs_err_pid2640.log*
    *# If you would like to submit a bug report, please visit:*
    *# http://java.sun.com/webapps/bugreport/crash.jsp*
    Anyone have idea how to solve this error.
    Thanks in advance.

    This error is created whenever things go sour on the native side. The first thing you can try, and I assume you are using a Java<->C++<->C# bridge which includes two dlls, one created by C++ and another by C#. Is to make sure that the C# dll is compiled using /t:module switch during compilation.
    If you are using VS2008, or VS2005, you can add a post build syntax like:
    csc /t:module /out:"$(ProjectDir)$(OutDir)YourModule.dll" "$(ProjectDir)YourCSfile.cs"
    Hope this helps! If not, ensure first that the native code works by creating a native test app for it.

Maybe you are looking for

  • Problem with unit in Query

    Hallo Experts, We encounter a problem with unit in our Query. Szenario: We use the Unit like PC, SET in Query. In Table T006 those Units have value 0 in the field ANDEC, so they will be rounded up and rounded down in Query. Our Problem is some Querie

  • PP CS6 Title Safe Motion Automatic Drop Shadow - WHY and how do I turn it off?

    Hello all. I'm new to Premiere (one week) after years on Avid. So go easy on me. I've created a title that I've added some motion to (basic stuff, just moved the position/added some directional blur so that the camera pan matches the title movement).

  • Calling subtemplate in standalone BIP

    Hi, I've created one main template and two subtemplate. All template have different dataset. I want to print that sub template in separate page based on condition. like Page1-Main template Page2-Subtemplate1(if condition=true) conditon is related to

  • Why key figures are not displaying

    Dear Experts, I am faced with a problem not encountered before. My report has multiple key figures all of which are not displayed when I run the query. However if I change the view to Tabular format (from query properties) the key figures become visi

  • E540 - update to BIOS 1.61 not working

    This forum was GREAT help when I encountered the not-rebooting properly problem after installing the Lenovo Small Business stuff - initially I was having to disconnect the CMOS battery each reboot, but after uninstalling that software, things seemed