Page 1 of 2 12 LastLast
Results 1 to 20 of 40
  1. #1
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default How to write output data to a file

    Hello,

    I'm developing a application that reads data by means of serial port and displays it into a JAVA GUI application in form of graphics and text fields.

    Now i want to save this output data into a file with the following columns:

    - Time (sec);
    - System Time (sec);
    - Temp (șC);
    - Patm (mBar);
    - Posm - Patm (mBar);
    - Posm (mBar);

    The data from Patm, Posm-Patm and Posm are output data in the JAVA application.
    Time is the time interval of the readings.
    System Time is the data and time of the system.
    Temp is the temperature that I will define later, but I want to prepare th file with this column also.

    Can somebondy help me with this and supply me with an example code. I'm a beginner in JAVA.

    Thanks you so much in advance

    Best regards

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Have a look at the I & O section of the Sun/Oracle Java Tutorials where you'll find decent instruction and plenty of sample code. Then if your code fails, come on back with it and we can have a look at it ourselves. Much luck.

    edit: here's where to start: http://download.oracle.com/javase/tu.../io/index.html
    Again, I wish you much luck!
    Last edited by Fubarable; 07-30-2010 at 07:39 PM.

  3. #3
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default

    Hello,
    thank you for your reply. I have done some research and I found the following sample code. However, I don't know how to both write the columns that I want and to receive the data from variable that are in another class, such like Posm, Patm and Posm-Patm.

    package ploter;

    import java.util.StringTokenizer;
    import java.io.*;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Formatter;


    public class NewMain {

    static Formatter fmt;

    void FormatOutput(String var1, String var2, String var3) throws IOException
    {
    fmt.format("%1$-10s %2$-23s %3$-10s%n", var1, var2, var3);
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) throws IOException{
    // TODO code application logic here
    try{
    String[][] data = {
    {"1111", "1", "10.33"},
    {"2222", "1", "10.34"},
    {"3333", "1", "10.35"},
    {"4444", "1", "10.36"},
    {"5555", "1", "10.37"}};
    // Create file
    NewMain formatt = new NewMain();
    FileWriter out = new FileWriter("RecordData.txt", true);
    BufferedWriter buf = new BufferedWriter(out);
    fmt = new Formatter(buf);
    fmt.format("%1$62s%n", "Impulse ResearchTime [sec] date and time //system time");

    for(int n=0; n<data.length; n++)
    {
    formatt.FormatOutput(data[n][0], data[n][1], data[n][2]);
    }
    //Close the output stream
    fmt.close();
    }catch (Exception e){//Catch exception if any
    System.err.println("Error: " + e.getMessage());
    }

    }

    }

    I don't understand the defined format of the sample code. I'm a beginner in JAVA.
    Can you help me modify this code so that I can accomplish my goal?

    Best regards

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,607
    Rep Power
    23

    Default

    Sounds like you should start with a simpler program and get a basic understanding of how OOP programming in java works.

    Isolate each of your problems into a small, simple program and solve it separately. Then merge the logic into the large program.
    receive the data from variable that are in another class,
    For this problem write two classes and use getter methods in one class to return values to the other class. The first class must have a reference to the second class to be able to call its getter methods.

  5. #5
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default

    Hello,

    I tried to simplify the code:

    Java Code:
    package ploter;
    
    import java.util.StringTokenizer;
    import java.io.*;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Formatter;
    
    
    public class NewMain {
    
        private PloterView data;
    
        public NewMain(PloterView pl){
            this.data = data;
        }
    
        /**
         * @param args the command line arguments
         */
        String ResA = data.CH0_val.getText();
        String ResB = data.CH1_val.getText();
        String Res = data.RES.getText();
    
        public static void main(String[] args) throws IOException{
            // TODO code application logic here
                try{
    
                    String data [][6]= {System Time, Time, 20, ResB, ResA, Res};
    		// Create file
                    FileWriter out = new FileWriter("RecordData.txt", true);
                    BufferedWriter buf = new BufferedWriter(out);
                    out.write("System Time    Time [sec]     Temp[șC]     Patm [mBar]     Patm+Posm [mBar]     Posm[mBar]"); 
    		//Close the output stream
    		out.close();
                    
                }catch (Exception e){//Catch exception if any
    			System.err.println("Error: " + e.getMessage());
                }
        }
    
    }
    I already brought the data from the other class PloterView (which includes the output data) to the main.

    Now I want to create in the file the following columns:

    Java Code:
    System Time    Time [sec]     Temp[șC]     Patm [mBar]     Patm+Posm [mBar]     Posm[mBar]

    And the data will be written in the corresponding columns.
    To do that I have the following instruction:

    String data [][6]= {System Time, Time, 20, ResB, ResA, Res};

    It is a error in this instruction, but I don't know how to write the data into the respective column.

    Can somebody help me with this?

    Best regards
    Last edited by Fubarable; 07-31-2010 at 03:36 PM.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Please use code tags when posting code as it makes your code more readable and understandable. I've taken the liberty of editing your post above, and to learn to do this yourself, please read the link in my signature.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Myself, I'd consider using a PrintWriter object that takes your FileWriter as a parameter of its constructor. Then I'd use the printf("...", ...) method to print out my data in a nice organized matter.

  8. #8
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default

    Ok, thank you for editing my code and I apologize for this.

    Can somebody help me, please?

    Best regards

  9. #9
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default

    Ok. But I'm not understanding very well what you are tried to explain to me.

    Can you give me an example so that I can understand it better?

    Best regards

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,607
    Rep Power
    23

    Default

    know how to write the data into the respective column
    What do you need help with?
    Have you looked at using the printf() method to format your output?

    You can put data in columns by using tabs or by inserting spaces.
    If you want the data right adjusted in each column, you'll need to add spaces to short fields to make them the same width as the longest field.

    Create a small test program to work out the techniques for getting column alignment.
    Use System.out.print statements and vary the data to print to see how to get your alignment.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Have a look at this tutorial here: Formatting (The Java™ Tutorials > Essential Classes > Basic I/O)
    Note that the format method in the tutorial works the same as the PrintWriter's printf method.

    For example a simple example that uses printf:

    PrintWriterDemo.java
    Java Code:
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    
    public class PrintWriterDemo {
       public static final String IN_FILE_PATH = "pwdInFile.txt"; // in my prog is "src/yr2010/m07/e/pwdInFile.txt"
       public static final String OUT_FILE_PATH = "pwdOutFile.txt"; // in my prog is "src/yr2010/m07/e/pwdOutFile.txt"
       public static final String FORMAT_STR = "%10s: %7s %7s %7s %7s %7s %7s %7s %n";
    
       public static void main(String[] args) {
          Scanner inScanner = null;
          PrintWriter out = null;
    
          try {
             inScanner = new Scanner(new File(IN_FILE_PATH));
             FileWriter filewriter = new FileWriter(OUT_FILE_PATH);
             out = new PrintWriter(filewriter);
    
             while (inScanner.hasNextLine()) {
                String line = inScanner.nextLine().trim();
                if (!line.isEmpty()) {
                   String[] tokens = line.split("\\s+");
                   if (tokens.length == 8) {
                      out.printf(FORMAT_STR, tokens[0], tokens[1], tokens[2], tokens[3], tokens[4],
                               tokens[5], tokens[6], tokens[7]);
                   }
                }
             }
          } catch (IOException e) {
             e.printStackTrace();
          } finally {
             if (out != null) {
                out.close();
             }
             if (inScanner != null) {
                inScanner.close();
             }
          }
       }
    }

    pwdInFile.txt
    Java Code:
    Month Sun Mon Tues Wed Thurs Fri Sat
    January 1 2 3 4 5 6 7
    February 2 3 4 5 6 7 8
    March 3 4 5 6 7 8 9
    April 4 5 6 7 8 9 0
    May 5 6 7 8 9 0 1
    June 6 7 8 9 0 1 2
    July 7 8 9 0 1 2 3

    creates this file:
    pwdOutFile.txt
    Java Code:
         Month:     Sun     Mon    Tues     Wed   Thurs     Fri     Sat 
       January:       1       2       3       4       5       6       7 
      February:       2       3       4       5       6       7       8 
         March:       3       4       5       6       7       8       9 
         April:       4       5       6       7       8       9       0 
           May:       5       6       7       8       9       0       1 
          June:       6       7       8       9       0       1       2 
          July:       7       8       9       0       1       2       3

  12. #12
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default

    Hello again,

    I've tried to follow your suggestions.

    The code that I have until now is the following:

    Java Code:
    package ploter;
    
    import java.util.StringTokenizer;
    import java.io.*;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Formatter;
    import java.io.File;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import txrx.SerialComm;
    
    public class NewMain {
    
        private SerialComm ValA, ValB, ResA, ResB, Res;
    
        public NewMain(SerialComm data){
            this.ValA = ValA;
            this.ValB = ValB;
            this.ResA = ResA;
            this.ResB = ResB;
            this.Res = Res;
        }
    
        public static final String FORMAT_STR = "%7s %7s %n";
    
        public static void main(String[] args) throws IOException{
    
            PrintWriter out1 = null;
    
                try{
    		// Create file
                    FileWriter calib1 = new FileWriter("Calib_1.txt", true);
                    BufferedWriter buf = new BufferedWriter(calib1);
                    out1 = new PrintWriter(calib1);
    
                    out1.printf(FORMAT_STR,"#    Time [sec]  Posm[mBar]");
                    out1.printf(FORMAT_STR, Res);
    
    		//Close the output stream
    		out1.close();
    
                }catch (Exception e){//Catch exception if any
    			System.err.println("Error: " + e.getMessage());
                }
        }
    }
    An error comes in the following instruction:

    Java Code:
     out1.printf(FORMAT_STR, Res);
    How do I make to write the content of the variable Res in the file?

    And how can I extract the time that the reading of the resulting value was made, so that I can write this value too?

    An example of what I want to accomplish follows:

    Java Code:
    #    Time [sec]  Posm[mBar]
          5               20
          10              21
          15              20
          20              20.5
          25              21
    Can somebody help me?

    Thank you in advance.

    Best regards

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,607
    Rep Power
    23

    Default

    An error comes in the following instruction:
    Please copy and paste the full text of the error message here.

    There must be one variable in the list of variables to print for every % in the format string. You only have one variable, the format string has 3 %s.

    how can I extract the time that the reading of the resulting value was made
    See the System.currentTimeMillis() method.
    Last edited by Norm; 08-01-2010 at 07:58 PM.

  14. #14
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default

    The error message for the variable Res is the following:

    Java Code:
    non-static variable Res cannot be referenced from a static context
    The variables I want to write in the file are the reading time and the value of the variable Res.

    Java Code:
    public static final String FORMAT_STR = "%g %g %n";
    
    out1.printf("%s","#    Time [sec]  Posm[mBar]");
    out1.printf(FORMAT_STR,Time+Res);
    The "%n" I copy from the example you provided me with previously.

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,607
    Rep Power
    23

    Default

    non-static variable Res cannot be referenced from a static context
    Res is a non-static member of the class and no class object has been created yet.

    If you are doing everything in a static method (main) then
    either make all your variables static
    or make them all local to the main method

  16. #16
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default

    Ok.

    But how do I do that?

    Do you think it is better to create another class or how do I make all variables static?

    Can you give me a simple example?

  17. #17
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    Java Code:
    String data [][6]= {System Time, Time, 20, ResB, ResA, Res};
    
    It is a error in this instruction, but I don't know how to write the data into the respective column. 
    
    Can somebody help me with this?
    If you want to save your data on 2d array you must set size of it rows and columns
    But if you want to save your data and you don't know (at first point) size of 2d array, then you should use Collections (List, ArrayList, LinkedList, Vector,...).

  18. #18
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,607
    Rep Power
    23

    Default

    how do I make all variables static
    Add "static" to the definition of all the variables.

    Here is a line of code from your program that defines a static String:
    public static final String FORMAT_STR = "%7s %7s %n";

  19. #19
    xana is offline Member
    Join Date
    Jul 2010
    Posts
    17
    Rep Power
    0

    Default

    Ok.

    I done that.

    Now i have the following code:

    Java Code:
    package ploter;
    
    import java.util.StringTokenizer;
    import java.io.*;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Formatter;
    import java.io.File;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import txrx.SerialComm;
    
    public class NewMain {
    
        public NewMain(SerialComm data){
            this.ValA = ValA;
            this.ValB = ValB;
            this.ResA = ResA;
            this.ResB = ResB;
            this.Res = Res;
        }
    
        private static SerialComm ValA, ValB, ResA, ResB, Res;
        public static String time;
    
        public static void main(String[] args) throws IOException{
    
            PrintWriter out1 = null;
            PrintWriter out2 = null;
            PrintWriter out3 = null;
    
                try{
    		// Create file of osmotic pressure variations
                    FileWriter pressure = new FileWriter("PressureVariations.txt", true);
                    BufferedWriter buf = new BufferedWriter(pressure);
                    out1 = new PrintWriter(pressure);
                    out1.printf("%s %n","#   Time [sec]  Posm[mBar]");
                    out1.printf("%s","    "+time);
                    out1.printf("%s %n","    "+Res);
    		//Close the output stream
    		out1.close();
    
                    // Create file of osmotic sensor calibration
                    FileWriter calib_1 = new FileWriter("CalibOsmotic.txt", true);
                    BufferedWriter buf1 = new BufferedWriter(calib_1);
                    out2 = new PrintWriter(calib_1);
                    out2.printf("%s %n","#   Voltage [V]  P[mBar]");
                    out2.printf("%s","    "+ValA);
                    out2.printf("%s %n","    "+ResA);
    		//Close the output stream
    		out2.close();
    
                    // Create file of reference sensor calibration
                    FileWriter calib_2 = new FileWriter("CalibReference.txt", true);
                    BufferedWriter buf2 = new BufferedWriter(calib_2);
                    out3 = new PrintWriter(calib_2);
                    out3.printf("%s %n","#   Voltage [V]  P[mBar]");
                    out3.printf("%s","    "+ValB);
                    out3.printf("%s %n","    "+ResB);
    		//Close the output stream
    		out3.close();
                    
                }catch (Exception e){//Catch exception if any
    			System.err.println("Error: " + e.getMessage());
                }
        }
    
    }
    I have no error, but warnings in this:

    Java Code:
        public NewMain(SerialComm data){
            this.ValA = ValA;
            this.ValB = ValB;
            this.ResA = ResA;
            this.ResB = ResB;
            this.Res = Res;
        }
    These warnings only appear after i added:

    Java Code:
    private static SerialComm ValA, ValB, ResA, ResB, Res;
    These warning say:

    Java Code:
    Assignment to itself
    Accessing Static Field ValA
    the same for the other variables ValA, ValB, ResA, ResB and Res.

    Do you know why these warnings appear?

  20. #20
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,607
    Rep Power
    23

    Default

    You are mixing doing everything in the main() method
    with trying to have a class with a constructor.

    Do either one or the other.

    When you do the computations in the main() method, then all the variables it uses must either be local to main or static if they are class variables. If you are only using the main method, get rid of the class constructor.

    Why are you doing the computations in main() vs in the constructor or a method in the class?

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 8
    Last Post: 05-12-2010, 07:19 PM
  2. Replies: 1
    Last Post: 02-04-2010, 09:17 PM
  3. taking data from recent output file
    By sara12345 in forum New To Java
    Replies: 3
    Last Post: 01-05-2010, 11:48 PM
  4. Where i have to write the common data to jsp
    By trill in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 08-07-2007, 07:35 AM
  5. Replies: 1
    Last Post: 07-24-2007, 02:02 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •