How to store something in text file?

Hello
I have question and i do not know how to do this.
can any one explain for me how i can save something in a text file.
i create calculator,and there is one question i need to do it:((Store the record of the session in a text file. ))
what i need to write some codes and so on.
please can u give idea ?

Alena,
Here's my static FileUtilz class, which includes a writeFile method, and several other handy methods.
package krc.io;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Arrays;
public abstract class FileUtilz
    public static final int bfrSize = 4096;
    public static void writeFile(String content, String filename)
    throws IOException
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileWriter(filename));
            out.write(content);
        } finally {
            //try {if(out!=null)out.close();}catch(Exception ignore){}
            out.close();
    public static String readFile(String filename)
    throws IOException, FileNotFoundException
        FileReader in = null;
        StringBuffer out = new StringBuffer();
        try {
            in = new FileReader(filename);
            char[] cbuf = new char[bfrSize];
            int n = in.read(cbuf, 0, bfrSize);
            while(n > 0) {
                out.append(cbuf);
                n = in.read(cbuf, 0, bfrSize);
        } finally {
            //try {if(in!=null)in.close();}catch(Exception ignore){}
            in.close();
        return out.toString();
    public  static String[] readFileIntoArray(String filename)
    throws IOException, FileNotFoundException
        return readFileIntoList(filename).toArray(new String[0]);
    public  static List<String> readFileIntoList(String filename)
    throws IOException, FileNotFoundException
        BufferedReader in = null;
        List<String> out = new ArrayList<String>();
        try {
            in = new BufferedReader(new FileReader(filename));
            String line = null;
            while ( (line = in.readLine()) != null ) {
                out.add(line);
        } finally {
            try {if(in!=null)in.close();}catch(Exception e){}
        return out;
    public static byte[] readBytes(String filename)
    throws IOException, FileNotFoundException
      //start = System.currentTimeMillis();
      File file = new File(filename);
      byte[] out = new byte[(int)file.length()];
      InputStream in = new FileInputStream(file);
      int size = in.read(out);
      in.close();
      //System.out.println("readBytes("+filename+"="+size") took "+(System.currentTimeMillis()-start));
      return out;
    public static boolean isSameFile(String filenameA, String filenameB)
    throws IOException, FileNotFoundException
      File fileA = new File(filenameA);
      File fileB = new File(filenameB);
      //check for same physical file
      if( fileA.equals(fileB) ) return(true);
      //compare sizes
      if( fileA.length() != fileB.length() ) return(false);
      //compare contents (buffer by buffer)
      boolean same=true;
      InputStream inA = null;
      InputStream inB = null;
      try {
        inA = new FileInputStream(fileA);
        inB = new FileInputStream(fileB);
        byte[] bfrA = new byte[bfrSize];
        byte[] bfrB = new byte[bfrSize];
        int sizeA=0, sizeB=0;
        do {
          sizeA = inA.read(bfrA);
          sizeB = inA.read(bfrB);
          if ( sizeA != sizeB ) {
            same=false;
          } else if ( sizeA == 0 ) {
            //do nothing
          } else if ( !Arrays.equals(bfrA,bfrB) ) {
            same=false;
        } while (same && sizeA != -1);
      } finally {
        if(inA!=null)inA.close();
        if(inB!=null)inB.close();
      return(same);
    public static String basename(String path, boolean cutExtension)
        String fname = (new File(path)).getName();
        if (cutExtension) {
            int i = fname.lastIndexOf(".");
            if (i > 0) {
                fname = fname.substring(0,i);
        return fname;
    public static String dirname(String path)
        return (new File(path)).getParent();
}

Similar Messages

  • HELP ON HOW TO STORE OUTPUT IN TEXT FILE

    Hello,
    I am trying to output the results from queties into an output text file does anyone knows how to do that please?
    For example i want to do :
    Select SYSDATE from dual;
    and output the result of it in a text file called output.txt does anyone knows how to do that please?
    THanks a lot and every help is appreciated.
    Regards,
    giannis

    Can i set the path of the output file Yes, you can :
    TEST@db102 SQL> spool /tmp/output.txt
    TEST@db102 SQL> select sysdate from dual;
    SYSDATE
    14-JUN-06
    TEST@db102 SQL> spool off
    TEST@db102 SQL> !ls -ltr /tmp | tail -n 1
    -rw-r--r--   1 ora102 dba       313 Jun 14 01:52 output.txt
    TEST@db102 SQL> !cat /tmp/output.txt
    TEST@db102 SQL> select sysdate from dual;
    SYSDATE
    14-JUN-06
    TEST@db102 SQL> spool off
    TEST@db102 SQL>                                                             

  • How to store multiple format text file in a oracle table

    Hi,
    I want to store a file which has multiple format for field separation so is it possible in Oracle data integrator if yes then how .....
    Waiting for reply
    regards
    palash

    Hello,
    <p>Read this article.</p>
    Francois

  • How To Store pdf or doc file in Oracle Database using Java Jdbc?

    can any one help me out How To Store pdf or doc file in Oracle Database using Java Jdbc in JSP/Serlet? i tried like anything. using blob also i tried. but i am able 2 store images in DB not files. please if u know or else if u have some code like this plz send that to me, and help me out plz. i need that urgent.

    Hi.. i am not getting error, But i am not getting the original contents from my file. i am getting all ASCII vales, instead of my original data. here i am including my code.
    for Adding PDF in DB i used image.jsp
    Database table structure (table name. pictures )
    Name Null? Type
    ID NOT NULL NUMBER(11)
    IMAGE BLOB
    <%@ page language="java" import="java.util.*,java.sql.*,java.io.*" pageEncoding="ISO-8859-1"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%
    try{
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
         PreparedStatement ps,pstmt,psmnt;
         ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
    File file =
    new File("D:/info.pdf");
    FileInputStream fs = new FileInputStream(file);
    ps.setInt(1,4);
    ps.setBinaryStream(2,fs,fs.available());
    int i = ps.executeUpdate();
    if(i!=0){
    out.println("<h2>PDF inserted successfully");
    else{
    out.println("<h2>Problem in image insertion");
    catch(Exception e){
    out.println("<h2>Failed Due To "+e);
    %>
    O/P: PDF inserted successfully
    i tried to display that pdf using servlet. i am giving the code below.
    import java.io.IOException;
    import java.sql.*;
    import java.io.*;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class DispPDF extends HttpServlet {
         * The doGet method of the servlet. <br>
         * This method is called when a form has its tag value method equals to get.
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         public void service(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
              //response.setContentType("text/html"); i commented. coz we cant use response two times.
              //PrintWriter out = response.getWriter();
              try{
                   InputStream sPdf;
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
                        PreparedStatement ps,pstmt,psmnt;
                   psmnt = con.prepareStatement("SELECT image FROM pictures WHERE id = ?");
                        psmnt.setString(1, "4"); // here integer number '4' is image id from the table.
                   ResultSet rs = psmnt.executeQuery();
                        if(rs.next()) {
                   byte[] bytearray = new byte[1048576];
                        //out.println(bytearray);
                        int size=0;
                        sPdf = rs.getBinaryStream(1);
                        response.reset();
                        response.setContentType("application/pdf");
                        while((size=sPdf.read(bytearray))!= -1 ){
                        //out.println(size);
                        response.getOutputStream().write(bytearray,0,size);
                   catch(Exception e){
                   System.out.println("Failed Due To "+e);
                        //out.println("<h2>Failed Due To "+e);
              //out.close();
    OP
    PDF-1.4 %âãÏÓ 2 0 obj <>stream xœ+är á26S°00SIá2PÐ5´1ôÝ BÒ¸4Ü2‹ŠKüsSŠSŠS4C²€ê P”kø$V㙂GÒU×713CkW )(Ü endstream endobj 4 0 obj <>>>/MediaBox[0 0 595 842]>> endobj 1 0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7 0000000000 65535 f 0000000325 00000 n 0000000015 00000 n 0000000413 00000 n 0000000168 00000 n 0000000464 00000 n 0000000509 00000 n trailer <<01b2fa8b70ac262bfa939cc786f8770c>]/Root 5 0 R/Size 7/Info 6 0 R>> startxref 641 %%EOF
    plz help me out.

  • How do I open a text file to sort using bubble sort?

    Hi,
    I have a text file, which is a list of #'s.. ex)
    0.001121
    0.313313
    0.001334
    how do you open a text file and read a list? I have the bubble sort code which sorts.. thanks

    I wrote this, but am getting a couple errors:
    import java.util.*;
    import java.io.*;
    public class sort
         public static void main(String[] args)
              String fileName = "numsRandom1024.txt";
              Scanner fromFile = null;
              int index = 0;
              double[] a = new double[1024];Don't use double. You should use something that implements Comparable, like java.lang.Double.
              try
                   fromFile = new Scanner(new File(fileName));
              catch (FileNotFoundException e)
    System.out.println("Error opening the file " +
    " + fileName);
                   System.exit(0);
              while (fromFile.hasNextLine())
                   String line = fromFile.nextLine();
                   a[index] = Double.parseDouble(line);Don't parse to a double, create a java.lang.Double instead.
                   System.out.println(a[index]);
                   index++;
              fromFile.close();
              bubbleSort( a, 0, a.length-1 );No. Don't use a.length-1: from index to a.length-1 all values will be null (if you use Double's). Call it like this:bubbleSort(a, 0, index);
    public static <T extends Comparable<? super T>> void
    d bubbleSort( T[] a, int first, int last )
              for(int counter = 0 ; counter < 1024 ; counter++)
    for(int counter2 = 1 ; counter2 < (1024-counter) ;
    ) ; counter2++)Don't let those counter loop to 1024. The max should be last .
                        if(a[counter2-1] > a[counter2])No. Use the compareTo(...) method:if(a[counter2-1].compareTo(a[counter2]) > 0) {
                             double temp = a[counter2];No, your array contains Comparable's of type T, use that type then:T temp = a[counter2];
    // ...Good luck.

  • How do I get a text file from Photoshop  to work in the main sequence in pp?

    How do I get a text file to work properly in the master sequence. I moved it from Photoshop, which I learned to do from a tutorial, but when I move the animated text sequence to the master, it either isnt running, or it is scaled way too big. How do I get it to run in the main sequence?

    "Wont Work Here" !  Does not mean much.
    Are you having an audio or a video issue? 
    Looks like no video clip on the video layer above that section of audio.
    I am teaching myself this stuff completely on the fly
    I suggest you do the Basic Tutorials ( Adobe TV for example) in both Premiere Pro and PhotoShop.
    You need to be competent in the basics and fundamentals of these apps and that will also help you describe and discuss the issues.   Check the 'Products on this site....
    Adobe TV

  • How to read a whole text file into a pl/sql variable?

    Hi, I need to read an entire text file--which actually contains an email message extracted from a content management system-- into a variable in a pl/sql package, so I can insert some information from the database and then send the email. I want to read the whole text file in one shot, not just one line at a time. Shoud I use Utl_File.Get_Raw or is there another more appropriate way to do this?

    how to read a whole text file into a pl/sql variable?
    your_clob_variable := dbms_xslprocessor.read2clob('YOUR_DIRECTORY','YOUR_FILE');
    ....

  • How to read the whole text file lines using FTP adapter

    Hi all,
    How to read the whole text file lines when error occured middle of the text file reading.
    after it is not reading the remaining lines . how to read the whole text file using FTP adapter
    pls can you help me

    Yes there is you need to use the uniqueMessageSeparator property. Have a look at the following link for its implementation.
    http://download-west.oracle.com/docs/cd/B31017_01/integrate.1013/b28994/adptr_file.htm#CIACDAAC
    cheers
    James

  • How to scan/ read a text file, pick up only lines you wanted.

    I'm new to Labview, I trying to wire a VI which can read a text file
    example below:
    Example: My Text File:
    1 abcd
    2 efgh
    8 aaaa
    1 uuuu
    and pick out only any line which start with number 1 (i.e 1 abcd)
    then output these 2 lines out to a a new text file?
    Thanks,
    Palmtree

    Hi,
    How do you creat your text files? Depending on the programm, there is added characters in the beginning and at the and of the file. So here you will find a VI to creat "raw" text files.
    To debug your VIs, use the probs and breakpoints, so you can solve the problem by your self or give an more accurate description of it.
    There is also the VI that read a integer and two strings  (%d %s %s)
    Attachments:
    creat text file.vi ‏9 KB
    read_from_file.vi ‏14 KB

  • How to write data to text file using external tables

    can anybody tell how to write data to text file using external tables concept?

    Hi,
    Using external table u can load the data in your local table in database,
    then using your local db table and UTL_FILE pacakge u can wrrite data to text file
    external table
    ~~~~~~~~~~~
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_7002.htm#i2153251
    UTL_FILE
    ~~~~~~~~~
    http://download-east.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_file.htm#sthref14093
    Message was edited by:
    Nicloei W
    Message was edited by:
    Nicloei W

  • How to append paragraph in text file of TextEdit application using applescript

    how to append paragraph in text file of TextEdit application using applescript and how do i save as different location.

    christian erlinger wrote:
    When you want to print out an escape character in java (java is doing the work in client_text_io ), you'd need to escape it.
    client_text_io.put_line(out_file, replace('your_path', '\','\\'));cheersI tried replacing \ with double slash but it just printed double slash in the bat file. again the path was broken into two lines.
    file output
    chdir C:\\DOCUME~1\
    195969\\LOCALS~1\\Temp\
    Edited by: rivas on Mar 21, 2011 6:03 AM

  • How to store xml data into file in xml format through java program?

    HI Friends,
    Please let me know
    How to store xml data into file in xml format through java program?
    thanks......
    can discuss further at messenger.....
    Avanish Kumar Singh
    Software Engineer,
    Samsung India Development Center,
    Bangalore--560001.
    [email protected]

    Hi i need to write the data from an XML file to a Microsoft SQL SErver database!
    i got a piece of code from the net which allows me to parse th file:
    import java.io.IOException;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import org.apache.xerces.parsers.SAXParser;
    import java.lang.*;
    public class MySaxParser extends DefaultHandler
    private static int INDENT = 4;
    private static String attList = "";
    public static void main(String[] argv)
    if (argv.length != 1)
    System.out.println("Usage: java MySaxParser [URI]");
    System.exit(0);
    String uri = argv[0];
    try
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    MySaxParser MySaxParserInstance = new MySaxParser();
    parser.setContentHandler(MySaxParserInstance);
    parser.parse(uri);
    catch(IOException ioe)
    ioe.printStackTrace();
    catch(SAXException saxe)
    saxe.printStackTrace();
    private int idx = 0;
    public void characters(char[] ch, int start, int length)
    throws SAXException
    String s = new String(ch, start, length);
    if (ch[0] == '\n')
    return;
    System.out.println(getIndent() + " Value: " + s);
    public void endDocument() throws SAXException
    idx -= INDENT;
    public void endElement(String uri, String localName, String qName) throws SAXException
    if (!attList.equals(""))
    System.out.println(getIndent() + " Attributes: " + attList);
    attList = "";
    System.out.println(getIndent() + "end document");
    idx -= INDENT;
    public void startDocument() throws SAXException
    idx += INDENT;
    public void startElement(String uri,
    String localName,
    String qName,
    Attributes attributes) throws SAXException
    idx += INDENT;
    System.out.println('\n' + getIndent() + "start element: " + localName);
    if (localName.compareTo("Machine") == 0)
    System.out.println("YES");
    if (attributes.getLength() > 0)
    idx += INDENT;
    for (int i = 0; i < attributes.getLength(); i++)
    attList = attList + attributes.getLocalName(i) + " = " + attributes.getValue(i);
    if (i < (attributes.getLength() - 1))
    attList = attList + ", ";
    idx-= INDENT;
    private String getIndent()
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < idx; i++)
    sb.append(" ");
    return sb.toString();
    }// END PRGM
    Now , am not a very good Java DEv. and i need to find a soln. to this prob within 1 week.
    The next step is to write the data to the DB.
    Am sending an example of my file:
    <Start>
    <Machine>
    <Hostname> IPCServer </Hostname>
    <HostID> 80c04499 </HostID>
    <MachineType> sun4u [ID 466748 kern.info] Sun Ultra 5/10 UPA/PCI (UltraSPARC-IIi 360MHz) </MachineType>
    <CPU> UltraSPARC-IIi at 360 MHz </CPU>
    <Memory> RAM : 512 MB </Memory>
    <HostAdapter>
    <HA> kern.info] </HA>
    </HostAdapter>
    <Harddisks>
    <HD>
    <HD1> c0t0d0 ctrl kern.info] target 0 lun 0 </HD1>
    <HD2> ST38420A 8.2 GB </HD2>
    </HD>
    </Harddisks>
    <GraphicCard> m64B : PCI PGX 8-bit +Accel. </GraphicCard>
    <NetworkType> hme0 : Fast-Ethernet </NetworkType>
    <EthernetAddress> 09:00:30:C1:34:90 </EthernetAddress>
    <IPAddress> 149.51.23.140 </IPAddress>
    </Machine>
    </Start>
    Note that i can have more than 1 machines (meaning that i have to loop thru the file to be able to write to the DB)
    Cal u tellme what to do!
    Even better- do u have a piece of code that will help me understand and implement the database writing portion?
    I badly need help here.
    THANX

  • How to create and read text file using LabVIEW 7.1 PDA module?

    How to create and read text file using LabVIEW 7.1 PDA module? I can not create a text file and read it.
    I attach my code here.
    Attachments:
    File_IO.vi ‏82 KB

    Well my acquisition code runs perfect. The problem is reading it. I can't seem to read my data no matter what I do. My data gets saved as a string using the array to string vi but I've read that the string to array vi (which I need to convert back to array to read my data) does not work on the pda. I'm using version 8.0. So I was trying to modify the program posted in this discussion so that it would save data from my DAQ. I did that but I still can't read the data after its saved. I really don't know what else to do. All I need to do is read the data on the pda itself. I can't understand why I'm having such a hard time doing that. I found a possible solution on another discussion that talks about parsing the strings because of the bug in the "string to array" vi. However, that lead me to another problem because for some reason, the array indicators or graphs don't function on the pda. When i build the program to the pda or emulator, the array indicators are faded out on the front panel as if the function is not valid. Does this kind of help give a better picture of what I'm trying to do. Simply read data back. Thanks.

  • How to Store something in a text file.

    Store the record of the session in a text file.
    please can any one tell me how can i create this thing.
    i cerate the button but does not work correctly and i can not save any calculation/
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.lang.Math.*;
    import java.math.BigInteger;
    public class Calculator2 extends JFrame implements ActionListener{
    JLabel lN1, lN2,lN3;//here are the Label.
    JTextField tN1, tN2;// here the place for the text field.
    JButton btnAdd,btnSub,btnMul,btnDiv,btnClear,btnSave; JTextArea outArea;//all our Button which are in the program.
    Calculator2(){//constructor.
    Box box=Box.createVerticalBox();//creation of the box.
    // input
    lN1=new JLabel("Write first number"); box.add(lN1);//creation of the input,the number which we want use.
    tN1=new JTextField(100); tN1.setEditable(true); box.add(tN1);//allows or prevents the user editing the text
    lN2=new JLabel("write second number"); box.add(lN2);
    tN2=new JTextField(100); tN2.setEditable(true); box.add(tN2);
    // buttons
    btnAdd=new JButton("+"); btnAdd.addActionListener(this); box.add(btnAdd);// button of addition operation
    // setPreferredSize();
    btnSub=new JButton("-"); btnSub.addActionListener(this); box.add(btnSub);// button of subtraction operation
    btnMul=new JButton("*"); btnMul.addActionListener(this); box.add(btnMul);// button of multiplication operation
    btnDiv=new JButton("/"); btnDiv.addActionListener(this); box.add(btnDiv);// button of division operation
    btnClear=new JButton("Clear"); btnClear.addActionListener(this); box.add(btnClear);// button of Clear operation
    btnSave=new JButton("Save"); btnSave.addActionListener(this); box.add(btnSave);// button of save operation
    // Output
    String desc="This is a simple integer calculator\n";//here the out put with text area.
    outArea=new JTextArea(desc,30,60);//out put area with the hight and length.
    ScrollPane scrollPane=new ScrollPane();//Creates an empty (no viewport view) JScrollPane where both horizontal and vertical scrollbars appear when needed
    scrollPane.add(outArea);
    box.add(scrollPane);
    Container c=getContentPane();
    c.add(box);
    c.setBackground(Color.green);//back ground color.
    setTitle("Calculator");//title
    setSize(600,375);//size
    setVisible(true);// visiblity of the program.
    private void showStatus(String status) {
    lN3.setText(status);
    public void actionPerformed(ActionEvent actionEvent){
    if(actionEvent.getSource()==btnClear){
    outArea.selectAll(); outArea.cut();
    } else {
    String sN1=tN1.getText(), sN2=tN2.getText(), sOp="";
    BigInteger bN1=new BigInteger(sN1);
    BigInteger bN2=new BigInteger(sN2);
    BigInteger bRes=BigInteger.ZERO, bResDiv[]={BigInteger.ZERO,BigInteger.ZERO};
    BigInteger bRemainder=BigInteger.ZERO;
    if(actionEvent.getSource()==btnAdd){bRes=bN1.add(bN2); sOp=" + ";}
    if(actionEvent.getSource()==btnSub){bRes=bN1.subtract(bN2); sOp=" - ";}
    if(actionEvent.getSource()==btnMul){bRes=bN1.multiply(bN2); sOp=" * ";}
    if(actionEvent.getSource()==btnDiv){sOp=" / ";
                if(bN2.signum()!=0)bResDiv=bN1.divideAndRemainder(bN2);//Math.signum() tells you what sign a number is....
                //returns zero if the argument is zero, 1.0 if the argument is greater than zero,
                //-1.0 if the argument is less than zero
                bRes=bResDiv[0]; bRemainder=bResDiv[1];
    if(sOp.equals(" / ") && bN2.signum()==0){
    // showStatus("Cannot divide by zero");
    } else {
    outArea.append(bN1.toString() + sOp+bN2.toString() + " = " + bRes.toString() + "\n");
    if(actionEvent.getSource()==btnDiv)outArea.append("Remainder = "+bRemainder.toString()+"\n");
    public static void main(String[] args) {//the main method of the program.
    new Calculator2().setVisible(true);
    }

    // This is a simple calculator that calculate 4 mathematical operations, addition,
    // subtraction, multiplication and division.
    // Author: Jean Chedid.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.lang.Math.*;
    import java.math.BigInteger;
    public class Calculator2 extends JFrame implements ActionListener{
        JLabel lN1, lN2,lN3;//here are the Label.
        JTextField tN1, tN2;// here the place for the text field.
        JButton btnAdd,btnSub,btnMul,btnDiv,btnClear,btnSave; JTextArea outArea;//all our Button which are in the program.
        Calculator2(){//constructor.
            Box box=Box.createVerticalBox();//creation of the box.
            // input
            lN1=new JLabel("Write first number"); box.add(lN1);//creation of the input,the number which we want use.
            tN1=new JTextField(100); tN1.setEditable(true); box.add(tN1);//allows or prevents the user editing the text
            lN2=new JLabel("write second number"); box.add(lN2);
            tN2=new JTextField(100); tN2.setEditable(true); box.add(tN2);
            // buttons
            btnAdd=new JButton("+"); btnAdd.addActionListener(this); box.add(btnAdd);// button of addition operation
            // setPreferredSize();
            btnSub=new JButton("-"); btnSub.addActionListener(this); box.add(btnSub);// button of subtraction operation
            btnMul=new JButton("*"); btnMul.addActionListener(this); box.add(btnMul);// button of multiplication operation
            btnDiv=new JButton("/"); btnDiv.addActionListener(this); box.add(btnDiv);// button of division operation
            btnClear=new JButton("Clear"); btnClear.addActionListener(this); box.add(btnClear);// button of Clear operation
            btnSave=new JButton("Save"); btnSave.addActionListener(this); box.add(btnSave);// button of save operation
            // Output
            String desc="This is a simple integer calculator\n";//here the out put with text area.
            outArea=new JTextArea(desc,30,60);//out put area with the hight and length.
            ScrollPane scrollPane=new ScrollPane();//Creates an empty (no viewport view) JScrollPane where both horizontal and vertical scrollbars appear when needed
            scrollPane.add(outArea);
            box.add(scrollPane);
            Container c=getContentPane();
            c.add(box);
            c.setBackground(Color.green);//back ground color.
            setTitle("Calculator");//title
            setSize(600,375);//size
            setVisible(true);// visiblity of the program.
         private void showStatus(String status) {
         lN3.setText(status);
        public void actionPerformed(ActionEvent actionEvent){
            if(actionEvent.getSource()==btnClear){
                outArea.selectAll(); outArea.cut();
            } else {
                String sN1=tN1.getText(), sN2=tN2.getText(), sOp="";
                BigInteger bN1=new BigInteger(sN1);
                BigInteger bN2=new BigInteger(sN2);
                BigInteger bRes=BigInteger.ZERO, bResDiv[]={BigInteger.ZERO,BigInteger.ZERO};
                BigInteger bRemainder=BigInteger.ZERO;
                if(actionEvent.getSource()==btnAdd){bRes=bN1.add(bN2); sOp=" + ";}
                if(actionEvent.getSource()==btnSub){bRes=bN1.subtract(bN2); sOp=" - ";}
                if(actionEvent.getSource()==btnMul){bRes=bN1.multiply(bN2); sOp=" * ";}
                if(actionEvent.getSource()==btnDiv){sOp=" / ";
                if(bN2.signum()!=0)bResDiv=bN1.divideAndRemainder(bN2);//Math.signum() tells you what sign a number is....
                //returns zero if the argument is zero, 1.0 if the argument is greater than zero,
                //-1.0 if the argument is less than zero
                bRes=bResDiv[0]; bRemainder=bResDiv[1];
                if(sOp.equals(" / ") && bN2.signum()==0){
                    // showStatus("Cannot divide by zero");
                } else {
                    outArea.append(bN1.toString() + sOp+bN2.toString() + " = " + bRes.toString() + "\n");
                    if(actionEvent.getSource()==btnDiv)outArea.append("Remainder = "+bRemainder.toString()+"\n");
        public static void main(String[] args) {//the main method of the program.
            new Calculator2().setVisible(true);
    }

  • How do I read a text file line by line and store to array

    I have a text file, I want to be able to store each line of the file in an array, how would I go about doing this? code example? tutorial? Thank you

    Well, you got the pseudo code:
    a) read line
    b) add to array
    So whats the problem? What don't you know how to do?
    What does your text book tell you about reading files. I'm sure it has an example, every book I've read does.
    By the way I would use an ArrayList to store each line of text, that way you don't need to know in advance.

Maybe you are looking for

  • Error #1065: Variable  is not defined on ObjectUtil??

    One comment to Adobe, it would be nice if the debugger would output better errors. Maybe it's just my lack of experience, but trying to track down errors is a daunting task. I had spent an entire night trying to track down this error and it has come

  • Adobe Premiere Elements 8 Hangs Crashes Errors - Vista 32

    Hi, First I'll admit i'm no pro (obviously why im using elements), so if im doing something amatuerish it's because i'm not a professional. I remember using adobe premiere elements 3 a while ago, and it ran fine. I just bought Premiere Elements 8 and

  • Multiple managed libraries: facebook issues (photos disappear)

    I reorganized my aperture libraries by moving projects to their appropriate library from my "working" library. Unfortunately, I published facebook albums from the working library. After I moved the projects to the appropriate library and trashed the

  • ORA-12705 setting up repo in Oracle DB

    After "lh setup" to configure repo when using Oracle 10g XE, I recieve message com.waveset.util.ConfigurationError: ==> java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-12705: Cannot access NLS data files or invalid envir

  • Publish and Save button is gone (blogs)

    I'm tring to publish my blog in Adobe Business Catalyst, and the "Save and Publish" button is gone. At the botton is just says Update, Save Draft, Preview, and Delete. Is there another way to publish it? Thanks! Danielle