Writing to .txt file

Hi
Thanks for any help and advice i got with my last problem, an other small problem i have. I'm tring to use a gui to write information to a file, its compling with no errors, creates the file but won't write any thing to it. I have it inside the try and catch no luck i've tried it out side the try and catch also. The same problem
Any help would be great i know its only something small just can't see it
Cheers
Ambrose
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
public class Create_Mail extends JPanel implements ActionListener
private JButton b1;
private JButton b4;
private JButton b2;
private JButton b3;
private JLabel l4;
private JLabel l5;
private JTextArea ta6;
private JComboBox comb7;
private JTextField t8;
private JTextField t9;
private JButton b10;
private FileOutputStream fos;
     private PrintWriter out;
public Create_Mail() {
//construct preComponents
String[] jcomp7Items = {"Ireland", "IP 1", "IP 2", "IP 3", "IP 4", "IP 5", "America", "IP1", "IP2", "IP3"};
//construct components
b1 = new JButton ("Save E-Mail");
b4 = new JButton ("a");
b2 = new JButton ("Exit System");
b3 = new JButton ("Main Menu");
l4 = new JLabel (" To :");
l5 = new JLabel (" Subject :");
ta6 = new JTextArea (5, 5);
comb7 = new JComboBox (jcomp7Items);
t8 = new JTextField (5);
t9 = new JTextField (5);
b10 = new JButton ("Calculate Size of E-Mail");
//adjust size and set layout
setPreferredSize (new Dimension (482, 488));
setLayout (null);
//add components
add (b4);
add (b1);
add (b2);
add (b3);
add (l4);
add (l5);
add (ta6);
add (comb7);
add (t8);
add (t9);
add (b10);
//set component bounds
b1.setBounds (35, 360, 100, 20);
b2.setBounds (160, 395, 105, 20);
b3.setBounds (160, 360, 100, 20);
b4.setBounds (100, 460, 95, 20);
b10.setBounds (285, 360, 180, 20);
l4.setBounds (25, 30, 100, 25);
l5.setBounds (25, 80, 100, 25);
ta6.setBounds (30, 150, 435, 165);
comb7.setBounds (365, 35, 95, 20);
t8.setBounds (135, 85, 210, 20);
t9.setBounds (135, 35, 210, 20);
          b1.addActionListener(this);
          b2.addActionListener(this);
          b3.addActionListener(this);
          b4.addActionListener(this);
          b10.addActionListener(this);
public void actionPerformed( ActionEvent e )
//When the user hits the below button a comparsion is made
//If it's true then its executes
//The process is continued depending on the button the user hits
System.out.println("button => "+ e.getActionCommand());
if(( new String("a")).compareTo(e.getActionCommand()) == 0 )
System.exit(0);
if(( new String("Save E-Mail")).compareTo(e.getActionCommand()) == 0 )
try
          fos = new FileOutputStream("E-mail.txt", true );
out = new PrintWriter(new OutputStreamWriter(fos));
     String s1 = ta6.getText();
               String s2 = t8.getText();
               String s3 = t9.getText();
               s1.trim();
               s2.trim();
               s3.trim();
               System.out.println("Test in dos prompt");
               out.println(s1 +"," s2 "," +s3);
               ta6.setText("");
               t8.setText("");
               t9.setText("");     
          catch (Exception ex){}
public static void main (String[] args)
JFrame frame = new JFrame ("Create_Mail");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
System.out.println("fgfd");
frame.getContentPane().add (new Create_Mail());
frame.pack();
frame.setVisible (true);
}

Hello Ambrose,
for writing text into a file use a Writer, e.g.
BufferedWriter outfile = new BufferedWriter(new FileWriter("E-mail.txt"));
String s= s1 +"," +s2 +"," +s3;
outfile.write(s,0,s.length());
outfile.newLine();hth
J�rg

Similar Messages

  • Problem with writing into txt file on the Web

    Hello friends - please could you give me an advice? Java console says:
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission http:\web.telecom.cz\jiriczech\xanado.txt write)
    Thank you a lot in advance:)!!

    The place you are trying to write the file to does not have write permission.

  • Writing in txt file

    hello
    I want to write a new line in an txt existing file
    public static void writeMessage(String msg,String logMod)
              try {
                 BufferedWriter out = new BufferedWriter(new FileWriter(getLogFile(logMod), true));
                 out.write(msg);
                 out.close();
             } catch (IOException e) {
         }the new line ca not be written what shoud be the problem
    thanks

    your code seems to be correct.
    1- check if you have a non null/empty message
    2 - check if the target file exists and if you have Write/write rights,
    3- print the stacktrace (e.printStackTrace()) and post the error code
    4- If still not working, try a simple code like the following:
         public static void main(String[] args) {
              try {
                   BufferedWriter out = new BufferedWriter(new FileWriter("D:/test.txt", true));
                   out.write("abcdef");
                   out.close();
              } catch (IOException e) {
                   e.printStackTrace();
         }hth

  • Problem on reading and writing from from a *.txt file

    I get Problem on reading and writing from from a *.txt file. The following is the read() method...
    The software said the DataInputStream is depreciated. Can anyone help me please?
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        String str = "";
        try
          in = new BufferedReader(file);
          //in = new FileInputStream(file);
          for(;;)
            str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);
      }

    Thank you for your reply. I have made some change. However, there is an incompetable type found error.
    in = new BufferedReader(new InputStreamReader(in));The following are all of the code.
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        //BufferedReader in = null;
        String str = "";
        try
          in = new BufferedReader(new InputStreamReader(in));
          //in = new FileInputStream(file);
          for(;;)
            BufferedReader Bstr = new BufferedReader(new InputStreamReader(in));
            //str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);

  • Writing the ASCII value of a character found in a .txt file

    I have a program that reads in a file and outputs certain characters to a new smaller file. The program works fine (thanks to some forum help) but I now need to print the ASCII value of the characters that are written to the file.
    The problem I'm having (besides writing the ascii value of the char) is that the Unix .txt file has some weird properties. When I run the program on a .txt test file that I created with spaces in it, the program ignores the space characters.
    Yet, when I run the program on the Unix file it wites the 'spaces' to the output file. That is why I want to write/print the ASCII value of the "blank "character in the Unix .txt file.
    I already serached the forum and did a Google search for Char to ASCII conversion but I didn't find anything.
    Thanks,
    LS6v
    Here's the code and the clips of the ouput files:
    package source;
    import javax.swing.*;
    import java.io.*;
    public class Scanner4
         public static void main(String[] args)
              getContents();
              System.exit(0);
         public static void getContents()
              char charArray[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                                         'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                                           '0','1','2','3','4','5','6','7','8','9','$','.', '#', '-', '/', '*', '&', '(', ')',' '};
              String Chars = null;
              String lineSep = System.getProperty("line.separator");
              int iterator = 0;
              int i = 0;
              int charNum = 1;
              int lineCount = 1;          
             // StringBuffer contents = new StringBuffer();
             //declared here only to make visible to finally clause
             BufferedReader input = null;
             BufferedWriter out = null;
             try {
                         //use buffering
                         //this implementation reads one line at a time
                         input = new BufferedReader( new FileReader( "C:\\testFile\\test1.txt" ));
                         out = new BufferedWriter( new FileWriter( "C:\\Scan file test\\Write\\test.txt" ));
                         String line = null;
                    out.write( "Character\tLine Number\tCharacter Number" + lineSep ); 
                              while (( line = input.readLine()) != null)
                               //contents.append(System.getProperty("line.separator"));
                               i = 0;
                               charNum = 1;
                               iterator = 0;
                              while( i < line.length() )
                                             for( int count = 0; count < charArray.length; count++)
                                                  if( (charArray[count] != line.charAt(iterator)) && (count+1 == charArray.length) )
                                                       out.write( "[" + line.charAt(iterator) + "]\t\t" + "[" + lineCount + "]\t\t" + "[" + charNum + "]" + lineSep);
                                                  if( charArray[count] == line.charAt(iterator) )
                                                       break;
                                        charNum +=1;
                                        iterator +=1;
                                        i++;                               
                                 lineCount +=1;
             catch (FileNotFoundException ex) {ex.printStackTrace();     System.out.println("File not found.");}          
                 catch (IOException ex){ex.printStackTrace();               System.out.println("IO Error.");}
             finally
                           try{
                                 if (input!= null){
                               //flush and close both "input" and its underlying FileReader
                                 input.close();
                                 out.close();
               catch (IOException ex){ex.printStackTrace();  System.out.println("IO Error #2.");}
    My created .txt file:
    1. a!asdsad
    2. @
    3. #
    4. $
    5. %sdfsdf
    6. ^
    7. &
    8. *
    9. (
    10. )
    11. _
    12. +sdfsdfsdf
    13. -
    14. =
    15. ~
    16. `
    17. dfgdfg;
    18. :
    19. '
    20. "fghfghf
    21. ,
    22. dfgdfg<
    23. .
    24. >fghfghfg
    25. /
    26. gggggggggggggggggggggggg?
    27. a
    Output for my .txt file:
    Character     Line Number     Character Number
    [!]          [1]          [5]
    [@]          [2]          [4]
    [%]          [5]          [4]
    [^]          [6]          [4]
    [_]          [11]          [5]
    [+]          [12]          [5]
    [=]          [14]          [5]
    [~]          [15]          [5]
    [`]          [16]          [5]
    [;]          [17]          [11]
    [:]          [18]          [5]
    [']          [19]          [5]
    ["]          [20]          [5]
    [,]          [21]          [5]
    [<]          [22]          [11]
    [>]          [24]          [5]
    [?]          [26]          [29]************************************************************************
    Output generated after reading the .txt file from the unix box:
    Character     Line Number     Character Number
    [ ]          [1]          [17]
    [ ]          [1]          [18]
    [ ]          [1]          [19]
    [ ]          [1]          [6530]
    [ ]          [2]          [2041]
    [']          [29]          [1834]
    [']          [29]          [2023]
    [']          [30]          [1834]
    [']          [30]          [2023]
    [']          [30]          [2066]
    [']          [47]          [2066]
    [']          [67]          [2067]
    [']          [77]          [2066]
    [+]          [80]          [28]

    Thanks I didn't even think to try and cast it to an int...
    The tool I'm using to create my .txt in windows is Notepad.
    I wrote a program to simply copy the original (3GB) Unix file and terminated it early so I could see what was there. What I found was some text and symbols and a lot of space between brief bursts of text. I can't really copy and paste an example because the amount of space is too large, it's basically a 3GB unformatted .txt file...
    Unix file was created on: unknown
    It sounds like the .txt file that I copied from the Unix box was formatted differently. But I thought that the formatting had more to do with end of line issues, not blank space between characters. Because a blank space should be seen by my program and ignored...
    Here's the ASCII value of the "blank" spaces:
    Character     Line Number     Character Number
    [ ]          [1]          [17]     Ascii Value: [0]
    [ ]          [1]          [18]     Ascii Value: [0]
    [']          [868]          [2066]     Ascii Value: [39]
    [,]          [877]          [186]     Ascii Value: [44]
    [,]          [877]          [276]     Ascii Value: [44]
    Also, the Ascii value printed for the blank spaces looks like the number zero here but it looks like it has strange points on the bottom of it in my output file. It looks like the extended ASCII character 234 &#937;

  • Only writing Integer pixel array to a .txt file,or showing in Frame

    Sir,
    I want to write integer values (range:0 to 255) to a .txt file .Actually after manipulating a .jpeg/.gif image I have gotten a 2D pixel array and a 1D pixel array that can be easily shown in console but I want to write this pixel array into a .txt file. Using of writeInt() is not working. Actually after using this faction the created file contain information which is non-alphanumeric /alphanumeric characters......
    following is error free the code: Plz. See only and only into the �class TestImage�and plz look after line marked by //�my_problem_to_be_resolved.�It is just few lines of code .I promise you will not be bothered.Plz��..
    import java.awt.*;
    import java.io.File;
    import java.io.FileWriter;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.awt.image.Raster;
    import java.awt.image.WritableRaster;
    class Image {
    protected int width,height;
    // 'samples' stores the image pixel values.
    protected int[][] samples;
    // Constructor: Reads the image from the
    // specified file name.
    public Image(String filename)
    throws Exception { read(filename); }
    // Returns the pixel width of the image.
    public int getWidth() { return width; }
    // Returns the pixel height of the image.
    public int getHeight() { return height; }
    // Reads the image from the specified file
    // name into the 'samples' array. Throws an
    // exception if the image is stored in an
    // unsupported file format (currently only
    // .GIF, .JPG, and .PNG are supported by Sun).
    public void read(String filename)
    throws Exception {
    // Extract the file name suffix.
    String ext = filename.substring
    (filename.indexOf('.')+1);
    // Create a file object for the file name.
    File fileImage = new File(filename);
    // Get a list of ImageReaders that claim
    // to be able to decode this image file
    // based on the file name suffix.
    Iterator imageReaders = ImageIO.
    getImageReadersBySuffix(ext);
    ImageReader imageReader;
    // Grab the first ImageReader in the list.
    if (imageReaders.hasNext())
    imageReader = (ImageReader)
    imageReaders.next();
    // If we get here we cannot decode the image.
    else throw new IIOException
    ("Unsupported image format");
    // Create a file input stream object to
    // read the image date.
    FileImageInputStream imageInputStream =
    new FileImageInputStream(fileImage);
    // Tell the ImageReader object to read data
    // from our file input stream object.
    imageReader.setInput(imageInputStream);
    // Get the width and height of the image.
    width = imageReader.getWidth(0);
    height = imageReader.getHeight(0);
    // Read the image from the file input stream,
    // and close the input stream when done.
    BufferedImage bufImage =
    imageReader.read(0);
    imageInputStream.close();
    // Get a raster object so we can extract the
    // pixel data from the BufferedImage.
    WritableRaster wRaster =
    bufImage.getRaster();
    // Create our 'samples' 2d-array.
    samples = new int[height][width];
    // Extract the image data into our 'samples'
    // array.
    for (int row = 0; row < height; row++)
    for (int col = 0; col < width; col++)
    samples[row][col] =
    wRaster.getSample(col,row,0);
    // Write the image stored in the 'samples'
    // array to the specified file. The file name
    // suffix should be a supported image file
    // format (currently either .JPG or .PNG).
    public void write(String filename)
    throws Exception {
    // Extract the file name suffix.
    String ext = filename.substring
    (filename.indexOf('.')+1);
    // Create a file object for the file name.
    File fileImage = new File(filename);
    // Get a list of ImageWriters that claim to
    // be able to encode images in the specified
    // image file format based on the file name
    // suffix.
    Iterator imageWriters = ImageIO.
    getImageWritersBySuffix(ext);
    ImageWriter imageWriter;
    // Grab the first ImageWriter in the list.
    if (imageWriters.hasNext())
    imageWriter = (ImageWriter)
    imageWriters.next();
    // If we get here we cannot encode the image.
    else throw new IIOException
    ("Unsupported image format");
    // Create a file output stream object to
    // write the image data.
    FileImageOutputStream imageOutputStream
    = new FileImageOutputStream
    (fileImage);
    // Tell the ImageWriter to use our file
    // output stream object.
    imageWriter.setOutput
    (imageOutputStream);
    // The ImageWriter.write() method expects a
    // BufferedImage. Convert our 'samples' array
    // into a BufferedImage.
    BufferedImage bufImage =
    createBufferedImage();
    // Encode the image to the output file.
    imageWriter.write(bufImage);
    imageOutputStream.close();
    // Draws the image stored in the 'samples'
    // array on the specified graphics context.
    public void draw(Graphics gc,int x,int y){
    BufferedImage bufImage =
    createBufferedImage();
    gc.drawImage(bufImage,x,y,null);
    // Converts the 'samples' array into a
    // BufferedImage object. Students do not have
    // to understand how this works.
    private BufferedImage
    createBufferedImage() {
    // Create a monochrome BufferedImage object.
    BufferedImage bufImage = new
    BufferedImage(width,height,
    BufferedImage.TYPE_BYTE_GRAY);
    // Create a WriteableRaster object so we can
    // put sample data into the BufferedImage
    // object's raster.
    WritableRaster wRaster =
    bufImage.getRaster();
    // Copy the 'samples' data into the
    // BufferedImage object's raster.
    for (int row = 0; row < height; row++)
    for (int col = 0; col < width; col++)
    wRaster.setSample
    (col,row,0,samples[row][col]);
    // Return the newly created BufferedImage.
    return bufImage;
    } // End of Class Image
    class TestImage {
    public static void main(String args[])
    throws Exception {
    // Create a frame to display the image.
    Frame frame = new Frame("Test Image");
    frame.setSize(1024,768);
    frame.setVisible(true);
    Graphics gc = frame.getGraphics();
    try {
    // Read the image from the file.
    Image img = new Image("C:/lilies.jpg");
    int height=img.getHeight();
    int width =img.getWidth();
    //�my_problem_to_be_resolved.�
         File image_object_arry=new File("C:/Image_array.txt");
         FileOutputStream image_object_arry_stream= new FileOutputStream(image_object_arry);
         DataOutputStream int_image_object_arry_stream=new DataOutputStream(image_object_arry_stream);
    //Conversion of two dimensional pixel arrry into one dimensional array
    int intPixels1[] = new int [height * width];
    int k = 0;
    for(int i = 0; i <= width; i++) {
    for(int j = 0; j <= height; j++) {
    intPixels1[k] = img.samples[i][j];
    int_image_object_arry_stream.writeInt((int) intPixels1[k]);
    // System.out.println(intPixels1[k]);
    k = k+1;
    import java.awt.*;
    import java.io.File;
    import java.io.FileWriter;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.awt.image.Raster;
    import java.awt.image.WritableRaster;
    class Image {
    protected int width,height;
    // 'samples' stores the image pixel values.
    protected int[][] samples;
    // Constructor: Reads the image from the
    // specified file name.
    public Image(String filename)
    throws Exception { read(filename); }
    // Returns the pixel width of the image.
    public int getWidth() { return width; }
    // Returns the pixel height of the image.
    public int getHeight() { return height; }
    // Reads the image from the specified file
    // name into the 'samples' array. Throws an
    // exception if the image is stored in an
    // unsupported file format (currently only
    // .GIF, .JPG, and .PNG are supported by Sun).
    public void read(String filename)
    throws Exception {
    // Extract the file name suffix.
    String ext = filename.substring
    (filename.indexOf('.')+1);
    // Create a file object for the file name.
    File fileImage = new File(filename);
    // Get a list of ImageReaders that claim
    // to be able to decode this image file
    // based on the file name suffix.
    Iterator imageReaders = ImageIO.
    getImageReadersBySuffix(ext);
    ImageReader imageReader;
    // Grab the first ImageReader in the list.
    if (imageReaders.hasNext())
    imageReader = (ImageReader)
    imageReaders.next();
    // If we get here we cannot decode the image.
    else throw new IIOException
    ("Unsupported image format");
    // Create a file input stream object to
    // read the image date.
    FileImageInputStream imageInputStream =
    new FileImageInputStream(fileImage);
    // Tell the ImageReader object to read data
    // from our file input stream object.
    imageReader.setInput(imageInputStream);
    // Get the width and height of the image.
    width = imageReader.getWidth(0);
    height = imageReader.getHeight(0);
    // Read the image from the file input stream,
    // and close the input stream when done.
    BufferedImage bufImage =
    imageReader.read(0);
    imageInputStream.close();
    // Get a raster object so we can extract the
    // pixel data from the BufferedImage.
    WritableRaster wRaster =
    bufImage.getRaster();
    // Create our 'samples' 2d-array.
    samples = new int[height][width];
    // Extract the image data into our 'samples'
    // array.
    for (int row = 0; row < height; row++)
    for (int col = 0; col < width; col++)
    samples[row][col] =
    wRaster.getSample(col,row,0);
    // Write the image stored in the 'samples'
    // array to the specified file. The file name
    // suffix should be a supported image file
    // format (currently either .JPG or .PNG).
    public void write(String filename)
    throws Exception {
    // Extract the file name suffix.
    String ext = filename.substring
    (filename.indexOf('.')+1);
    // Create a file object for the file name.
    File fileImage = new File(filename);
    // Get a list of ImageWriters that claim to
    // be able to encode images in the specified
    // image file format based on the file name
    // suffix.
    Iterator imageWriters = ImageIO.
    getImageWritersBySuffix(ext);
    ImageWriter imageWriter;
    // Grab the first ImageWriter in the list.
    if (imageWriters.hasNext())
    imageWriter = (ImageWriter)
    imageWriters.next();
    // If we get here we cannot encode the image.
    else throw new IIOException
    ("Unsupported image format");
    // Create a file output stream object to
    // write the image data.
    FileImageOutputStream imageOutputStream
    = new FileImageOutputStream
    (fileImage);
    // Tell the ImageWriter to use our file
    // output stream object.
    imageWriter.setOutput
    (imageOutputStream);
    // The ImageWriter.write() method expects a
    // BufferedImage. Convert our 'samples' array
    // into a BufferedImage.
    BufferedImage bufImage =
    createBufferedImage();
    // Encode the image to the output file.
    imageWriter.write(bufImage);
    imageOutputStream.close();
    // Draws the image stored in the 'samples'
    // array on the specified graphics context.
    public void draw(Graphics gc,int x,int y){
    BufferedImage bufImage =
    createBufferedImage();
    gc.drawImage(bufImage,x,y,null);
    // Converts the 'samples' array into a
    // BufferedImage object. Students do not have
    // to understand how this works.
    private BufferedImage
    createBufferedImage() {
    // Create a monochrome BufferedImage object.
    BufferedImage bufImage = new
    BufferedImage(width,height,
    BufferedImage.TYPE_BYTE_GRAY);
    // Create a WriteableRaster object so we can
    // put sample data into the BufferedImage
    // object's raster.
    WritableRaster wRaster =
    bufImage.getRaster();
    // Copy the 'samples' data into the
    // BufferedImage object's raster.
    for (int row = 0; row < height; row++)
    for (int col = 0; col < width; col++)
    wRaster.setSample
    (col,row,0,samples[row][col]);
    // Return the newly created BufferedImage.
    return bufImage;
    } // End of Class Image
    /*class TestImage {
    public static void main(String args[])
    throws Exception {
    // Create a frame to display the image.
    Frame frame = new Frame("Test Image");
    frame.setSize(1024,768);
    frame.setVisible(true);
    Graphics gc = frame.getGraphics();
    try {
    // Read the image from the file.
    Image img = new Image("C:/srk.jpg");
    // Display the image.
    img.draw(gc,10,40);
    // Flip the image upside down
    //img.flipX();
    // Display the flipped image.
    img.draw(gc,20+img.getWidth(),40);
    // Write the new image to a file
    img.write("HorseNew.jpg");
    } catch (Exception e) {
    System.out.println
    ("Exception in main() "+e.toString());
    class TestImage {
    public static void main(String args[])
    throws Exception {
    // Create a frame to display the image.
    Frame frame = new Frame("Test Image");
    frame.setSize(1024,768);
    frame.setVisible(true);
    Graphics gc = frame.getGraphics();
    try {
    // Read the image from the file.
    Image img = new Image("C:/lilies.jpg");
    int height=img.getHeight();
    int width =img.getWidth();
    File image_object_arry=new File("C:/Image_array.txt");
    FileOutputStream image_object_arry_stream=new FileOutputStream(image_object_arry);
         DataOutputStream int_image_object_arry_stream=new DataOutputStream(image_object_arry_stream);
    //Conversion of two dimensional pixel arrry into one dimensional array
    int intPixels1[] = new int [height * width];
    int k = 0;
    for(int i = 0; i <= width; i++) {
    for(int j = 0; j <= height; j++) {
    intPixels1[k] = img.samples[i][j];
    int_image_object_arry_stream.writeInt((int) intPixels1[k]);
    // System.out.println(intPixels1[k]);
    k = k+1;
    catch (Exception e) {
    System.out.println("Exception in main() "+e.toString());
    catch (Exception e) {
    System.out.println("Exception in main() "+e.toString());
    }

    My Friend, you need to put your code within CODE tags
    And I suspect if anyone would go through your code this way.
    Assuming your problem is to write pixel values to a file you may use this,
          try{
            // Create file
            FileWriter fstream = new FileWriter("out.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            for(int i =0; pixels.length() ; i++)
              out.write(pixels[i]+"\t");
           //Close the output stream
           out.close();
           }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }

  • Writing and reading txt file, GUI components

    <b>HI GUYS I AM JUST NEW TO JAVA AND I AM TRYING TO LEARN SOME MORE IN JAVA. SO I NEED HELP FROM YOU GREAT GUYS WHO KNOWS MORE & MORE THING THAN ME. I CODE A GUI FOR THIS PROGRAM. THE CODE IS BELOW. <b/>
    This program has to read a txt file to create Food objects which will consist of a food name, a serving size, and a number of calories. A text file is read which contains the calories contained in specific food items. From this data, an array of Food objects will be created and used to populate a combo box for user selection. The Food objects will also be used in calculating the balance calories for a given user on a given day.
    User input will be used to create User objects which will be user name, age, gender, height, weight, and Food Diary objects (composition). The Food Diary objects will consist of Date (composition), Food object (composition), number of servings, and a balance. Food Diary objects will consist of the activity on any given day (see text area in sample output screen below). All User objects are saved to a file as objects and can be retrieved on subsequent runs of the program.
    The program will calculate the number of calories the user is allowed per day to maintain the user�s current weight (see below for formula to use for this).
    BMRMen = 66 + (13.7 * weightPounds/2.2) + (5 * heightInches*2.54) - (6.8 * age)
    BMRWomen = 655 + (9.6 * weightPounds/2.2) + (1.8 * heightInches*2.54) - (4.7 * age)
    GUI CODE
    <code>
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FoodDiaryGUI extends JFrame implements ActionListener {
    JLabel lblName, lblAge, lblWeight,lblHeight,lblFemale,lblMale,lblFood;
    JTextField txtName, txtAge, txtWeight,txtHeight;
    JButton btnSave, btnNewUser;
    JTextArea outputArea;
    JComboBox cbFood;
    int currentIndex=0, lastIndex=4;
    public FoodDiaryGUI()
    super ("Food Diary Calculator");
    lblName= new JLabel("Name: ");
    lblAge= new JLabel("Age: ");
    lblWeight= new JLabel("Weight(lbs): ");
    lblHeight= new JLabel("Height(inches): ");
    lblFemale= new JLabel("Female: ");
    lblMale= new JLabel("Male: ");
    lblFood= new JLabel("Choose a Food: ");
    txtName= new JTextField(15);
    txtAge= new JTextField(3);
    txtWeight= new JTextField(6);
    txtHeight= new JTextField(6);
    outputArea= new JTextArea(9,20);
    cbFood= new JComboBox();
    cbFood.setPreferredSize(new Dimension(100, 20));
    Container c = getContentPane();
    JPanel northPanel = new JPanel();
    northPanel.setLayout(new FlowLayout());
    btnSave= new JButton("SAVE");
    northPanel.add(btnSave);
    btnNewUser= new JButton("NEW USER");
    northPanel.add(btnNewUser);
    btnSave.addActionListener(this);
    btnNewUser.addActionListener(this);
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new FlowLayout());
    centerPanel.add(lblName);
    centerPanel.add(txtName);
    centerPanel.add(lblAge);
    centerPanel.add(txtAge);
    centerPanel.add(lblWeight);
    centerPanel.add(txtWeight);
    centerPanel.add(lblHeight);
    centerPanel.add(txtHeight);
    centerPanel.setLayout(new FlowLayout());
    JRadioButton rbMale = new JRadioButton(maleString);
    birdButton.setMnemonic(KeyEvent.VK_M);
    birdButton.setActionCommand(maleString);
    birdButton.setSelected(true);
    JRadioButton rbFemale = new JRadioButton(femaleString);
    catButton.setMnemonic(KeyEvent.VK_F);
    catButton.setActionCommand(femaleString);
    //Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(rbMale);
    group.add(rbFemale);
    //Register a listener for the radio buttons.
    rbMale.addActionListener(this);
    rbFemale.addActionListener(this);
    public void actionPerformed(ActionEvent rb) {
    picture.setIcon(new ImageIcon("images/"
    + rb.getActionCommand()
    + ".gif"));
    radioGroup.add(rbMale);
    radioGroup.add(rbFemale);
    centerPanel.add(rbMale);
    centerPanel.add(rbFemale);
    centerPanel.add(lblFood);
    centerPanel.add(cbFood);
    JPanel southPanel = new JPanel();
    southPanel.setLayout(new FlowLayout());
    southPanel.add (outputArea);
    c.add(northPanel,BorderLayout.NORTH);
    c.add(centerPanel,BorderLayout.CENTER);
    c.add(southPanel,BorderLayout.SOUTH);
    setSize(650,300);
    setVisible(true);
    //add listener to button components.
    public void actionPreformed(ActionEvent e)
    if (e.getSource()==btnSave)
    currentIndex++;
    currentIndex--;
    public static void main (String[] args)
    FoodDiaryGUI application = new FoodDiaryGUI();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    </code>
    THE .txt file is as:
    1000 ISLAND, SALAD DRSNG,LOCAL*1 TBSP*25
    1000 ISLAND, SALAD DRSNG,REGLR*1 TBSP*60
    100% NATURAL CEREAL *1 OZ*135
    40% BRAN FLAKES, KELLOGG'S*1 OZ*90
    40% BRAN FLAKES, POST*1 OZ*90
    ALFALFA SEEDS, SPROUTED, RAW*1 CUP*10
    ALL-BRAN CEREAL*1 OZ*70
    ALMONDS, WHOLE*1 OZ*165
    ANGELFOOD CAKE, FROM MIX*1 PIECE*125
    APPLE JUICE, CANNED*1 CUP*115
    i hope this forum site has to many java professionals and this problem is nothing for them. for me it is great.

    Stick to using a single userid and a single posting of a question:
    http://forum.java.sun.com/thread.jspa?threadID=731264&tstart=0

  • READING AND WRITING TXT FILE, GUI COMPONENTS.

    HI GUYS I AM JUST NEW TO JAVA AND I AM TRYING TO LEARN SOME MORE IN JAVA. SO I NEED HELP FROM YOU GREAT GUYS WHO KNOWS MORE & MORE THING THAN ME. I CODE A GUI FOR THIS PROGRAM. THE CODE IS BELOW.
    This program has to read a txt file to create Food objects which will consist of a food name, a serving size, and a number of calories. A text file is read which contains the calories contained in specific food items. From this data, an array of Food objects will be created and used to populate a combo box for user selection. The Food objects will also be used in calculating the balance calories for a given user on a given day.
    User input will be used to create User objects which will be user name, age, gender, height, weight, and Food Diary objects (composition). The Food Diary objects will consist of Date (composition), Food object (composition), number of servings, and a balance. Food Diary objects will consist of the activity on any given day (see text area in sample output screen below). All User objects are saved to a file as objects and can be retrieved on subsequent runs of the program.
    The program will calculate the number of calories the user is allowed per day to maintain the user�s current weight (see below for formula to use for this).
    BMRMen = 66 + (13.7 * weightPounds/2.2) + (5 * heightInches*2.54) - (6.8 * age)
    BMRWomen = 655 + (9.6 * weightPounds/2.2) + (1.8 * heightInches*2.54) - (4.7 * age)
    GUI CODE
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FoodDiaryGUI extends JFrame implements ActionListener {
         JLabel               lblName, lblAge, lblWeight,lblHeight,lblFemale,lblMale,lblFood;
         JTextField          txtName, txtAge, txtWeight,txtHeight;
         JButton               btnSave, btnNewUser;
         JTextArea           outputArea;
         JComboBox          cbFood;
         int currentIndex=0, lastIndex=4;
         public FoodDiaryGUI()
              super ("Food Diary Calculator");
              lblName=               new JLabel("Name: ");
              lblAge=                    new JLabel("Age: ");
              lblWeight=               new JLabel("Weight(lbs): ");
              lblHeight=               new JLabel("Height(inches): ");
              lblFemale=               new JLabel("Female: ");
              lblMale=               new JLabel("Male: ");
              lblFood=               new JLabel("Choose a Food: ");
              txtName=               new JTextField(15);
              txtAge=                    new JTextField(3);
              txtWeight=               new JTextField(6);
              txtHeight=               new JTextField(6);
              outputArea=               new JTextArea(9,20);     
              cbFood=                    new JComboBox();
              cbFood.setPreferredSize(new Dimension(100, 20));
              Container c = getContentPane();
              JPanel northPanel = new JPanel();
              northPanel.setLayout(new FlowLayout());
              btnSave=               new JButton("SAVE");
              northPanel.add(btnSave);
              btnNewUser=               new JButton("NEW USER");
              northPanel.add(btnNewUser);
              btnSave.addActionListener(this);
              btnNewUser.addActionListener(this);
              JPanel centerPanel = new JPanel();
              centerPanel.setLayout(new FlowLayout());
              centerPanel.add(lblName);
              centerPanel.add(txtName);
              centerPanel.add(lblAge);
              centerPanel.add(txtAge);
              centerPanel.add(lblWeight);
              centerPanel.add(txtWeight);
              centerPanel.add(lblHeight);
              centerPanel.add(txtHeight);
              centerPanel.setLayout(new FlowLayout());
              JRadioButton rbMale = new JRadioButton(maleString);
         birdButton.setMnemonic(KeyEvent.VK_M);
         birdButton.setActionCommand(maleString);
         birdButton.setSelected(true);
         JRadioButton rbFemale = new JRadioButton(femaleString);
         catButton.setMnemonic(KeyEvent.VK_F);
         catButton.setActionCommand(femaleString);
         //Group the radio buttons.
         ButtonGroup group = new ButtonGroup();
         group.add(rbMale);
         group.add(rbFemale);
         //Register a listener for the radio buttons.
         rbMale.addActionListener(this);
         rbFemale.addActionListener(this);
         public void actionPerformed(ActionEvent rb) {
         picture.setIcon(new ImageIcon("images/"
         + rb.getActionCommand()
         + ".gif"));
              radioGroup.add(rbMale);
              radioGroup.add(rbFemale);
              centerPanel.add(rbMale);
              centerPanel.add(rbFemale);
              centerPanel.add(lblFood);
              centerPanel.add(cbFood);
              JPanel southPanel = new JPanel();
              southPanel.setLayout(new FlowLayout());
              southPanel.add (outputArea);
              c.add(northPanel,BorderLayout.NORTH);
              c.add(centerPanel,BorderLayout.CENTER);
              c.add(southPanel,BorderLayout.SOUTH);
              setSize(650,300);
              setVisible(true);
              //add listener to button components.
              public void actionPreformed(ActionEvent e)
                   if (e.getSource()==btnSave)
                        currentIndex++;
                        currentIndex--;
              public static void main (String[] args)
                   FoodDiaryGUI application = new FoodDiaryGUI();
                   application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              public void actionPerformed(ActionEvent arg0) {
                   // TODO Auto-generated method stub
    THE .txt file is as:
    1000 ISLAND, SALAD DRSNG,LOCAL*1 TBSP*25
    1000 ISLAND, SALAD DRSNG,REGLR*1 TBSP*60
    100% NATURAL CEREAL *1 OZ*135
    40% BRAN FLAKES, KELLOGG'S*1 OZ*90
    40% BRAN FLAKES, POST*1 OZ*90
    ALFALFA SEEDS, SPROUTED, RAW*1 CUP*10
    ALL-BRAN CEREAL*1 OZ*70
    ALMONDS, WHOLE*1 OZ*165
    ANGELFOOD CAKE, FROM MIX*1 PIECE*125
    APPLE JUICE, CANNED*1 CUP*115
    i hope this forum site has to many java professionals and this problem is nothing for them. for me it is great.

    Stick to using a single userid and a single posting of a question:
    http://forum.java.sun.com/thread.jspa?threadID=731264&tstart=0

  • Problem about writing txt file and  utl_put_line

    After some research on the internet I found the way how to writre files from Oracle 11g to a txt file.
    I read that utl_put_line only holds 32k per line and adds a new line at the end of each row but my problem it´s that if I want to open the file with SQL Server :D it doesn't recognize the CRLF so there is no end line and the last column has the data from the next row. The files are created on Linux so if I open them on Windows i have to convert into DOS format but if I try to open that file with Excel everything works fine, so I was wondering if there is a limit of columns or number of characters that can be on a txt file.
    There is my pl sql that I used to create my txt files:
    -------------------CODE-----------------------------
    declare
    cursor r1 is
    select * from dqstage.st_nomdetalle
    where sistema = 'NOR'
    and procesar = 0
    and identidad=02;
    cursor r2 ( p_parid number) is
    select * from dqstage.st_nomsubdetalle
    where par_id = p_parid
    and procesar = 0
    and sistema = 'NOR'
    and substr(nombrearchivo,6,2)=02;
    vcadena varchar2(4000);
    --vcadena1 varchar2(4000);
    vcadena1 clob;
    vcadena2 long;
    c number:=0;
    vencabezados long;
    archivo sys.utl_file.file_type;
    begin
    archivo:= SYS.UTL_FILE.FOPEN(location=>'UPEPE_DIR',filename=>'nor02.txt',open_mode=>'w',max_linesize=>32767);
    vencabezados :='FILEID|NOMBREARCHIVO|TIPOREGISTRO|IDENTIFICADORREGISTRO|FECHAEMISIONPAGO|CLAVETIPONOMINA|CLAVECT|TURNOCT|RFC|CURP|NUMEMPLEADOESTATAL'
    ||'|NUMSEGURIDADSOCIAL|NOMBRECOMPLETO|NOMBRES|PRIMERAPELLIDO|SEGUNDOAPELLIDO|CODIGOPAGADURIA|IDORIGENPRESUPUESTALPLAZA|CLAVEPRESUPUESTAL|'
    ||'PARTIDAPRESUPUESTAL|CODIGOPAGO|CLAVEUNIDAD|CLAVESUBUNIDAD|CLAVECATEGORIA|HSM|NUMEROPLAZA|CLAVENIVELPUESTO|CLAVENIVELSUELDO|ZONAECONOMICA|'
    ||'PERCEPCIONNETA|CLABECUENTA|NUMEROCHEQUE|CLAVEMOTIVOPAGORETROACTIVO|NUMTOTALPERDED|ERRORES|'
    ||'TIPOCONCEPTO1|CONCEPTOPAGO1|MONTO1|PERIODODEL1|PERIODOAL1|FUENTEFINANCIAMIENTO1|ORIGEN1|ERRORES1|'
    ||'TIPOCONCEPTO2|CONCEPTOPAGO2|MONTO2|PERIODODEL2|PERIODOAL2|FUENTEFINANCIAMIENTO2|ORIGEN2|ERRORES2|'
    ||'TIPOCONCEPTO3|CONCEPTOPAGO3|MONTO3|PERIODODEL3|PERIODOAL3|FUENTEFINANCIAMIENTO3|ORIGEN3|ERRORES3|'
    ||'TIPOCONCEPTO4|CONCEPTOPAGO4|MONTO4|PERIODODEL4|PERIODOAL4|FUENTEFINANCIAMIENTO4|ORIGEN4|ERRORES4|'
    ||'TIPOCONCEPTO5|CONCEPTOPAGO5|MONTO5|PERIODODEL5|PERIODOAL5|FUENTEFINANCIAMIENTO5|ORIGEN5|ERRORES5|'
    ||'TIPOCONCEPTO6|CONCEPTOPAGO6|MONTO6|PERIODODEL6|PERIODOAL6|FUENTEFINANCIAMIENTO6|ORIGEN6|ERRORES6|'
    ||'TIPOCONCEPTO7|CONCEPTOPAGO7|MONTO7|PERIODODEL7|PERIODOAL7|FUENTEFINANCIAMIENTO7|ORIGEN7|ERRORES7|'
    ||'TIPOCONCEPTO8|CONCEPTOPAGO8|MONTO8|PERIODODEL8|PERIODOAL8|FUENTEFINANCIAMIENTO8|ORIGEN8|ERRORES8|'
    ||'TIPOCONCEPTO9|CONCEPTOPAGO9|MONTO9|PERIODODEL9|PERIODOAL9|FUENTEFINANCIAMIENTO9|ORIGEN9|ERRORES9|'
    ||'TIPOCONCEPTO10|CONCEPTOPAGO10|MONTO10|PERIODODEL10|PERIODOAL10|FUENTEFINANCIAMIENTO10|ORIGEN10|ERRORES10|'
    ||'TIPOCONCEPTO11|CONCEPTOPAGO11|MONTO11|PERIODODEL11|PERIODOAL11|FUENTEFINANCIAMIENTO11|ORIGEN11|ERRORES11|'
    ||'TIPOCONCEPTO12|CONCEPTOPAGO12|MONTO12|PERIODODEL12|PERIODOAL12|FUENTEFINANCIAMIENTO12|ORIGEN12|ERRORES12|'
    ||'TIPOCONCEPTO13|CONCEPTOPAGO13|MONTO13|PERIODODEL13|PERIODOAL13|FUENTEFINANCIAMIENTO13|ORIGEN13|ERRORES13|'
    ||'TIPOCONCEPTO14|CONCEPTOPAGO14|MONTO14|PERIODODEL14|PERIODOAL14|FUENTEFINANCIAMIENTO14|ORIGEN14|ERRORES14|'
    ||'TIPOCONCEPTO15|CONCEPTOPAGO15|MONTO15|PERIODODEL15|PERIODOAL15|FUENTEFINANCIAMIENTO15|ORIGEN15|ERRORES15|'
    ||'TIPOCONCEPTO16|CONCEPTOPAGO16|MONTO16|PERIODODEL16|PERIODOAL16|FUENTEFINANCIAMIENTO16|ORIGEN16|ERRORES16|'
    ||'TIPOCONCEPTO17|CONCEPTOPAGO17|MONTO17|PERIODODEL17|PERIODOAL17|FUENTEFINANCIAMIENTO17|ORIGEN17|ERRORES17|'
    ||'TIPOCONCEPTO18|CONCEPTOPAGO18|MONTO18|PERIODODEL18|PERIODOAL18|FUENTEFINANCIAMIENTO18|ORIGEN18|ERRORES18|'
    ||'TIPOCONCEPTO19|CONCEPTOPAGO19|MONTO19|PERIODODEL19|PERIODOAL19|FUENTEFINANCIAMIENTO19|ORIGEN19|ERRORES19|'
    ||'TIPOCONCEPTO20|CONCEPTOPAGO20|MONTO20|PERIODODEL20|PERIODOAL20|FUENTEFINANCIAMIENTO20|ORIGEN20|ERRORES20|'
    ||'TIPOCONCEPTO21|CONCEPTOPAGO21|MONTO21|PERIODODEL21|PERIODOAL21|FUENTEFINANCIAMIENTO21|ORIGEN21|ERRORES21|'
    ||'TIPOCONCEPTO22|CONCEPTOPAGO22|MONTO22|PERIODODEL22|PERIODOAL22|FUENTEFINANCIAMIENTO22|ORIGEN22|ERRORES22|'
    ||'TIPOCONCEPTO23|CONCEPTOPAGO23|MONTO23|PERIODODEL23|PERIODOAL23|FUENTEFINANCIAMIENTO23|ORIGEN23|ERRORES23|'
    ||'TIPOCONCEPTO24|CONCEPTOPAGO24|MONTO24|PERIODODEL24|PERIODOAL24|FUENTEFINANCIAMIENTO24|ORIGEN24|ERRORES24|'
    ||'TIPOCONCEPTO25|CONCEPTOPAGO25|MONTO25|PERIODODEL25|PERIODOAL25|FUENTEFINANCIAMIENTO25|ORIGEN25|ERRORES25|'
    ||'TIPOCONCEPTO26|CONCEPTOPAGO26|MONTO26|PERIODODEL26|PERIODOAL26|FUENTEFINANCIAMIENTO26|ORIGEN26|ERRORES26|'
    ||'TIPOCONCEPTO27|CONCEPTOPAGO27|MONTO27|PERIODODEL27|PERIODOAL27|FUENTEFINANCIAMIENTO27|ORIGEN27|ERRORES27|'
    ||'TIPOCONCEPTO28|CONCEPTOPAGO28|MONTO28|PERIODODEL28|PERIODOAL28|FUENTEFINANCIAMIENTO28|ORIGEN28|ERRORES28|'
    ||'TIPOCONCEPTO29|CONCEPTOPAGO29|MONTO29|PERIODODEL29|PERIODOAL29|FUENTEFINANCIAMIENTO29|ORIGEN29|ERRORES29|'
    ||'TIPOCONCEPTO30|CONCEPTOPAGO30|MONTO30|PERIODODEL30|PERIODOAL30|FUENTEFINANCIAMIENTO30|ORIGEN30|ERRORES30|'
    ||'TIPOCONCEPTO31|CONCEPTOPAGO31|MONTO31|PERIODODEL31|PERIODOAL31|FUENTEFINANCIAMIENTO31|ORIGEN31|ERRORES31|'
    ||'TIPOCONCEPTO32|CONCEPTOPAGO32|MONTO32|PERIODODEL32|PERIODOAL32|FUENTEFINANCIAMIENTO32|ORIGEN32|ERRORES32|'
    ||'TIPOCONCEPTO33|CONCEPTOPAGO33|MONTO33|PERIODODEL33|PERIODOAL33|FUENTEFINANCIAMIENTO33|ORIGEN33|ERRORES33|'
    ||'TIPOCONCEPTO34|CONCEPTOPAGO34|MONTO34|PERIODODEL34|PERIODOAL34|FUENTEFINANCIAMIENTO34|ORIGEN34|ERRORES34|'
    ||'TIPOCONCEPTO35|CONCEPTOPAGO35|MONTO35|PERIODODEL35|PERIODOAL35|FUENTEFINANCIAMIENTO35|ORIGEN35|ERRORES35|'
    ||'TIPOCONCEPTO36|CONCEPTOPAGO36|MONTO36|PERIODODEL36|PERIODOAL36|FUENTEFINANCIAMIENTO36|ORIGEN36|ERRORES36|'
    ||'TIPOCONCEPTO37|CONCEPTOPAGO37|MONTO37|PERIODODEL37|PERIODOAL37|FUENTEFINANCIAMIENTO37|ORIGEN37|ERRORES37|'
    ||'TIPOCONCEPTO38|CONCEPTOPAGO38|MONTO38|PERIODODEL38|PERIODOAL38|FUENTEFINANCIAMIENTO38|ORIGEN38|ERRORES38|'
    ||'TIPOCONCEPTO39|CONCEPTOPAGO39|MONTO39|PERIODODEL39|PERIODOAL39|FUENTEFINANCIAMIENTO39|ORIGEN39|ERRORES39|'
    ||'TIPOCONCEPTO40|CONCEPTOPAGO40|MONTO40|PERIODODEL40|PERIODOAL40|FUENTEFINANCIAMIENTO40|ORIGEN40|ERRORES40|'
    ||'TIPOCONCEPTO41|CONCEPTOPAGO41|MONTO41|PERIODODEL41|PERIODOAL41|FUENTEFINANCIAMIENTO41|ORIGEN41|ERRORES41|'
    ||'TIPOCONCEPTO42|CONCEPTOPAGO42|MONTO42|PERIODODEL42|PERIODOAL42|FUENTEFINANCIAMIENTO42|ORIGEN42|ERRORES42|'
    ||'TIPOCONCEPTO43|CONCEPTOPAGO43|MONTO43|PERIODODEL43|PERIODOAL43|FUENTEFINANCIAMIENTO43|ORIGEN43|ERRORES43|'
    ||'TIPOCONCEPTO44|CONCEPTOPAGO44|MONTO44|PERIODODEL44|PERIODOAL44|FUENTEFINANCIAMIENTO44|ORIGEN44|ERRORES44|'
    ||'TIPOCONCEPTO45|CONCEPTOPAGO45|MONTO45|PERIODODEL45|PERIODOAL45|FUENTEFINANCIAMIENTO45|ORIGEN45|ERRORES45|'
    ||'TIPOCONCEPTO46|CONCEPTOPAGO46|MONTO46|PERIODODEL46|PERIODOAL46|FUENTEFINANCIAMIENTO46|ORIGEN46|ERRORES46|'
    ||'TIPOCONCEPTO47|CONCEPTOPAGO47|MONTO47|PERIODODEL47|PERIODOAL47|FUENTEFINANCIAMIENTO47|ORIGEN47|ERRORES47|'
    ||'TIPOCONCEPTO48|CONCEPTOPAGO48|MONTO48|PERIODODEL48|PERIODOAL48|FUENTEFINANCIAMIENTO48|ORIGEN48|ERRORES48|'
    ||'TIPOCONCEPTO49|CONCEPTOPAGO49|MONTO49|PERIODODEL49|PERIODOAL49|FUENTEFINANCIAMIENTO49|ORIGEN49|ERRORES49|'
    ||'TIPOCONCEPTO50|CONCEPTOPAGO50|MONTO50|PERIODODEL50|PERIODOAL50|FUENTEFINANCIAMIENTO50|ORIGEN50|ERRORES50';
    --||'TIPOCONCEPTO51|CONCEPTOPAGO51|MONTO51|PERIODODEL51|PERIODOAL51|FUENTEFINANCIAMIENTO51|ORIGEN51|ERRORES51';
    sys.utl_file.put_line(archivo, vencabezados);
    for i in r1 loop
    c:=c+1;
    vcadena := i.fileid||'|'||i.nombrearchivo||'|'||i.tiporegistro||'|'||i.identificadorregistro||'|'||i.fechaemisionpago||'|'||i.clavetiponomina||'|'||i.clavect||'|'||i.turnoct||'|'||i.rfc
    ||'|'||i.curp||'|'||i.numempleadoestatal||'|'||i.numseguridadsocial||'|'||i.nombrecompleto||'|'||i.nombres||'|'||i.primerapellido||'|'||i.segundoapellido||'|'||i.codigopagaduria
    ||'|'||i.idorigenpresupuestalplaza||'|'||i.clavepresupuestal||'|'||i.partidapresupuestal||'|'||i.codigopago||'|'||i.claveunidad||'|'||i.clavesubunidad||'|'||i.clavecategoria||'|'||i.hsm
    ||'|'||i.numeroplaza||'|'||i.clavenivelpuesto||'|'||i.clavenivelsueldo||'|'||i.zonaeconomica||'|'||i.percepcionneta||'|'||i.clabecuenta||'|'||i.numerocheque||'|'||i.clavemotivopagoretroactivo
    ||'|'||i.numtotalperded||'|'||i.errores;
    vcadena1:=null;
    for j in r2 (i.fileid) loop
    vcadena1 := vcadena1||'|'|| j.tipoconcepto||'|'||j.conceptopago||'|'||j.monto||'|'||j.periododel||'|'||j.periodoal||'|'||j.fuentefinanciamiento ||'|'||j.origen||'|'||j.errores;
    end loop;
    sys.utl_file.put_line(archivo, vcadena2);
    end loop;
    sys.utl_file.fclose(archivo);
    end;
    As you can see I write the column names first and with a loop I add the data, so I can have a very large column at the end.
    How can I add the CRLF at the end of each line to have it working with Windows?

    user2068122 wrote:
    After some research on the internet I found the way how to writre files from Oracle 11g to a txt file.
    I read that utl_put_line only holds 32k per line and adds a new line at the end of each row but my problem it´s that if I want to open the file with SQL Server :D it doesn't recognize the CRLF so there is no end line and the last column has the data from the next row. The files are created on Linux so if I open them on Windows i have to convert into DOS format but if I try to open that file with Excel everything works fine, so I was wondering if there is a limit of columns or number of characters that can be on a txt file.
    <snip>
    Oracle is simply passing a string of characters to the OS to be written to a file in the host OS's native text format. That format is different from Windows and nix.  Windows will append a CR-LF pair to the end of the provided character string, as its end-of-record delimiter.  nix will append only a CR (or is it LF?) as its end-of-record delimiter. This is purely and OS issue that Oracle knows or cares nothing about. It is also something that must always be kept in mind when passing files between *nix and Windows.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Writing scripts to edit or parse txt file How To?

    Not sure if this is the correct forum for programming type question. If not someone point me in the right direction?
    I'm a programming student and I'd like to teach myself some scripting skills over the summer break.
    In particular, I've got a txt file I'd like to split into three txt files. A google calendar file that I'd like to divide into three separate calendars.
    I know what strings I want to put where. My problem is what scripting language am I trying to use? Applescript? Something else?
    Any suggestions or ideas? Recommendations on reading materials or sample scripts I should look at?
    Thanks for the help.

    Perl is a huge programming language. A more expedient project would be to learn some basic shell commands such as sed, awk, tr and cut. The sed command is optimized for linewise operations, awk is optimized for columnwise operations and tr is a basic character translation tool especially useful when feeding Mac files into a UNIX command.
    Setting up sed and awk commands to read and write files is a big part of learning, especially since shell commands cannot normally write to a file in situ.
    Applescript is not ideal for text manipulation as it is slow, uses a bulky delimiter system and has irritating file access limitations. However it can be a powerful interface for the above mention shell commands. Applescript offers an ideal way to assemble shell commands with user-input variables. Of course, shell commands cannot be interactive with Applescript, so you learn to do incremental operations on text files.
    Another handy use for Applescript is to send your command to Terminal, which makes an ideal output display.

  • Accessing txt file in executable vi

    Hi,
    I have built a user interface for a project im working on. The data entered by the user on the interface is saved in a text file upon closing of the program. This is currently working fine but when I create an executable of my code, data is not written to the txt file upon closing. Is there some special way to build these types of VIs,
    The code for writing to the file is in a sub VI and i use the "Write to spreadsheet file" function, i pass in the reference of "C:\Documents and Settings\asha264\Desktop\Single Line\Single Line (9.0)\Data.txt".
    Thanking You,
    Adnan Sharief
    Solved!
    Go to Solution.

    Make sure that your means for signalling the other vi's to exit doesn't have an inadvertent race condition. Remember that LabVIEW is data flow language, that to make sure that certain events occur in a certain order that there is a signal dependecy to force the order of execution. I got bit by that recently when we used a functional global to signal all of the various programmatic loops in the various vi's when it was time to shut down. There was at least one place where, under certain conditions, the loop stop terminal was getting the signal before the "stuff" in the loop had executed. Putting an error in/out on the FG, then puting it in the error line after the functions (actually file writing) guaranteed that the file writes would occur before the "exit" condition was evaluated.
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

  • How to encypt a .txt file and how to decrypt a same .txt file when i need

    My requirement is i want to encrypt a .txt file and
    keep it in some folder. In that file we put database connection
    information. when ever we need that file we have to access it and decrypt
    it. with that decrypted values we have make connection with database.
    i am sending a code in which i wrote both encyption and decrytion in same file, but i want to do it separately.
    Please help me regarding this.
    package com.businessobjects;
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    public class EncryptDecrypt
         public static void EncodeIt()
              try
              // generate Cipher objects for encoding and decoding
              Cipher itsocipher1 = Cipher.getInstance("DES");
              Cipher itsocipher2 = Cipher.getInstance("DES");
              // generate a KeyGenerator object
              KeyGenerator KG = KeyGenerator.getInstance("DES");
              System.out.println("Using algorithm " + KG.getAlgorithm());
              // generate a DES key
              Key mykey = KG.generateKey();
              // initialize the Cipher objects
              System.out.println("Initializing ciphers...");
              itsocipher1.init(Cipher.ENCRYPT_MODE, mykey);
              itsocipher2.init(Cipher.DECRYPT_MODE, mykey);
              // creating the encrypting cipher stream
              //System.out.println("Creating the encrypting cipher stream...");
              /*FileInputStream fis = new FileInputStream("Original.txt");
    FileOutputStream fos = new FileOutputStream("Encypt.txt");
              CipherInputStream cis1 = new CipherInputStream(fis, itsocipher1);
              // creating the decrypting cipher stream
              //System.out.println("Creating the decrypting cipher stream...");
              byte[] b1 = new byte[8];
    int i1 = cis1.read(b1);
              while (i1 != -1)
                   fos.write(b1, 0, i1);
                   i1 = cis1.read(b1);
    fis.close();
    fos.close();*/
    // writing the decrypted data to output file
    FileInputStream fis1 = new FileInputStream("Encypt.txt");
    FileOutputStream fos1 = new FileOutputStream(Decypt.txt");
    CipherInputStream cis2 = new CipherInputStream(fis1, itsocipher2);
              byte[] b2 = new byte[8];
              int i2 = cis2.read(b2);
              while (i2 != -1)
                   fos1.write(b2, 0, i2);
                   i2 = cis2.read(b2);
    fis1.close();
              fos1.close();
    //cis1.close();
              cis2.close();
              catch (Exception e)
              System.out.println("Caught exception: " + e);
    With regards
    Pavankumar.

    here is the solution you wanted it
    uses password based encryption
    but your requirements are for very badly
    designed code
    This is the encryption part
    it converts the inputfile original.txt
    into the outputfile encrypt.txt which
    contains the original encrypted
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import javax.crypto.Cipher;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    public class PWBEncryption {
        // Salt
        static byte[] salt = {
            (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
            (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
        // Iteration count
        static int count = 20;
        public PWBEncryption() {
        // params:
        // password   -> the pasword used to create the key
        // inputfile  -> the file containing the stuff to be encrypted
        // i.e. original.txt
        // outputfile -> the file that will contain the encrypted stuff
        // i.e. encrypt.txt
        public static boolean doIt(char[] password,String inputfile,String outputfile){
            try{
                // Create PBE parameter set
                PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
                PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
                // create secretkey
                SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
                SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
                // create cipher
                Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
                pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
                // read input
                FileInputStream fis = new FileInputStream(inputfile);
                byte[] input = new byte[fis.available()];
                fis.read(input);
                // encrypt
                byte[] output = pbeCipher.doFinal(input);
                // write encrypted output
                FileOutputStream fos = new FileOutputStream(outputfile);
                fos.write(output);
                return true;
            catch(Exception e){
                System.out.println(e.toString());
                return false;
    }This is the decrypt part
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import javax.crypto.Cipher;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    public class PWBDecryption {
        // Salt
        static byte[] salt = {
            (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
            (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
        // Iteration count
        static int count = 20;
        public PWBDecryption() {
        // params:
        // password   -> the pasword used to create the key
        // inputfile  -> the file containing the decrypted data
        // i.e. encrypt.txt
        // outputfile -> the file that will contain the decrypted data
        // i.e. decrypt.txt
        public static boolean doIt(char[] password,String inputfile,String outputfile){
            try{
                // Create PBE parameter set
                PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
                PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
                // create secretkey
                SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
                SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
                // create cipher
                Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
                pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
                // read input
                FileInputStream fis = new FileInputStream(inputfile);
                byte[] input = new byte[fis.available()];
                fis.read(input);
                // encrypt
                byte[] output = pbeCipher.doFinal(input);
                // write encrypted output
                FileOutputStream fos = new FileOutputStream(outputfile);
                fos.write(output);
                return true;
            catch(Exception e){
                return false;
    }runner
    public class RunRun {
        public RunRun() {
        public static void main(String args[]){
            char password[] = {'q','w','e','r','t','y'};       
            boolean enc = PWBEncryption.doIt(password,"C:\\original.txt","c:\\encrypt.txt");
            System.out.println("Encryption status == "+enc);
            boolean dec = PWBDecryption.doIt(password,"c:\\encrypt.txt","c:\\decrypt.txt");
            System.out.println("Decryption status == "+dec);
    }

  • Populate a table reading the data from a TXT file

    how can I populate a table reading the data from a TXT file?
    thanks

    Hey Kevin!
    Using FORMS.TEXT_IO to bulk load data from a file strikes me as re-inventing the wheel. It is just about justifiable in a self-service environment, but I regard the EXTERNAL TABLE is a better solution for that situation as well.
    The same applies to UTL_FILE. I think the ability to read text with UTL_FILE is primarily intended for read file-based configuration or file manipulation/processing rather than data loading.
    Re-writing a text file into SQL statements is too much like hard work (even with an editor that supports macro definition and regular expressions) for no real benefit. You lose all the bulk load peformance you would get from SQL*Loader. But for QAD I'd probably let you off with it.
    You missed out one obvious alternative: using Java to turn the contents of an XML file into a CLOB and inserting it into a table which is read by a PL/SQL procedure that parses the XML records and insert the retrieved data into a table.
    Stay lucky, APC

  • Error while writing to a file

    Hi,
    I am getting an error while writing to a file.Here is the sample code in which I am getting error.The STDERR is getting printed to console but the same is not getting written to a file.
    package Sample;
    import java.util.*;
    import java.io.*;
    public class MediocreExecJavac
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("perl ic_start");
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    FileWriter fw=new FileWriter("result.txt");
    String line = null;
    System.out.println("<ERROR>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    fw.write(line);
    System.out.println("</ERROR>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    fw.close();
    } catch (Throwable t)
    t.printStackTrace();
    }Below is the output -
    <ERROR>
    Can't open perl script "ic_start": No such file or directory
    java.lang.NullPointerException
    at java.io.Writer.write(Unknown Source)
    at Sample.MediocreExecJavac.main(MediocreExecJavac.java:21)
    Please tell where the program is going wrong.

    i think it is just the path of file that u r missing

  • .INI files vs .TXT files for changing default values in a .EXE?

    Hi,
    I have a two-part question related to updating the default values of controls in an executable:
    I am creating a LabVIEW executable for installation on two different production-floor computers.   I need to be able to change the default values of the front panel controls (as I would do with the “make this value default” command during development). From reading prior posts, I understand that I could use the “Write Configuration Settings File.vi” and “Read Configuration Settings File.vi” to generate a .INI file that would be read by the .EXE and would establish the desired values of the controls. However when I took a look at the block diagrams for those configuration .VIs, they don’t appear (to me) to be any easier to use than just reading values from a spreadsheet file. IE: Instead of using these configuration files and a .INI file, could I not instead just read values from a .TXT file that contains the desired values?   I’ve never used a .INI file before, or had to worry about “keys” and “sections,” so from my (perhaps naïve) perspective, the .INI method seems less easy to use. Is there any advantage to the .INI format?
    Regardless of whether I use the .INI file or a .TXT file, I have this additional problem: One of the things that changes when I install my .EXE file on a new computer is the COM port numbers used by two serial devices.   (On my development computer, the two serial devices use COM5 and COM6, whereas on the two production-flood computers, the COM ports will almost certainly be different).   I suppose I could use the Device Manager on the production-floor computers to change the COM ports to be the same as those on my development computer, but I’d prefer to be able to (again) change the default value of the COM ports in my .EXE.   However, I’m not sure how to do that.   The configuration VIs, have options for reading / writing Booleans, strings, paths, and numeric, but not, (so far as I can tell) for a VISA class.
    Any thoughts / suggestions are welcome. Thanks.
    Solved!
    Go to Solution.

    Dan_the_Clam wrote:
    Thanks for your reply, Yamaeda,
    Great that I can use a string to open a VISA session - I had no idea.  I'll try that.  
    And - ah - you are right about the .INI files.  I just did an experiment in which I re-ordered the sections and randomly changed which letters were capitalized in the key values, and the "read configuration settings.VI" still read the file correctly.  Thanks for that.
    Unfortunately, in my existing code, the controls on the block-diagram aren't all co-located together; they are scattered throughout the block diagram - some of them in case structures and loops.   I suppose that means I'll have to move them all to the left side of the block diagram, route them to these "Write Key.VIs" and then wire them up into the cases and loops with fairly long wires.   It's just a hassle, and is going to make my block diagram more complicated.  Well, I suppose that's how one learns...
    Thanks again.
    dan
    Assuming you have a state machine and an Init state it's a fair use of Local Variables to update controls from the ini-file. The same goes for saving the values.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

Maybe you are looking for