Results 1 to 15 of 15
  1. #1
    Join Date
    Jan 2011
    Posts
    8
    Rep Power
    0

    Default Help With Outputting Data To A File

    Hi, I'm new here and am vaguely familiar to java but can't seem to get any combination of code to output the data I want to a file.

    Obviously the following is mostly taken from a tutorial.

    I want to output data under the "log" section to a new or already specified file (it doesn't matter to me.) It's marked by a comment about 2/3s of the way down the code. I'm trying to parse through stock data- ultimately.

    Thanks in advance, and sorry if I wasnt' clear enough

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    
    public class ReadWithScanner {
    
      public static void main(String... aArgs) throws FileNotFoundException {
        ReadWithScanner parser = new ReadWithScanner("C:/Documents and Settings/Owner/Desktop/Java Friendly Data.txt");
        parser.processLineByLine();
        log("Done.");
      }
      
      /**
       Constructor.
       @param aFileName full name of an existing, readable file.
      */
      public ReadWithScanner(String aFileName){
        fFile = new File(aFileName);  
      }
      
      /** Template method that calls {@link #processLine(String)}.  */
      public final void processLineByLine() throws FileNotFoundException {
        //Note that FileReader is used, not File, since File is not Closeable
        Scanner scanner = new Scanner(new FileReader(fFile));
        try {
          //first use a Scanner to get each line
          while ( scanner.hasNextLine() ){
            processLine( scanner.nextLine() );
          }
        }
        finally {
          //ensure the underlying stream is always closed
          //this only has any effect if the item passed to the Scanner
          //constructor implements Closeable (which it does in this case).
          scanner.close();
        }
      }
      
      /** 
       Overridable method for processing lines in different ways.
        
       <P>This simple default implementation expects simple name-value pairs, separated by an 
       '=' sign. Examples of valid input : 
       <tt>height = 167cm</tt>
       <tt>mass =  65kg</tt>
       <tt>disposition =  "grumpy"</tt>
       <tt>this is the name = this is the value</tt>
      */
      protected void processLine(String aLine){
        //use a second Scanner to parse the content of each line 
        Scanner scanner = new Scanner(aLine);
        scanner.useDelimiter(",");
        if ( scanner.hasNext() ){
          String name = scanner.next();		//A
          String name1 = scanner.next();	//B
          String name2 = scanner.next();	//C
          String name3 = scanner.next();	//D
          String name4 = scanner.next();	//E
          String name5 = scanner.next();	//F
          String name6 = scanner.next();	//G
          String name7 = scanner.next();	//H
          String name8 = scanner.next();	//I
          String name9 = scanner.next();	//J
          String name10 = scanner.next();	//K
          String name11 = scanner.next();	//L
          String name12 = scanner.next();	//M
          String name13 = scanner.next();	//N
          String name14 = scanner.next();	//O
          String name15 = scanner.next();	//P
          String name16 = scanner.next();	//Q
    //What I want to do is take the data below listed in the log parameter and write it to a file. and preferrably then drop down a line.
          	log(quote(name.trim()) + ", " + quote(name1.trim()) + ", " + quote(name2.trim())
          		  + ", " + quote(name3.trim()) + ", " + quote(name4.trim())
          		  + ", " + quote(name5.trim()) + ", " + quote(name6.trim())
          		  + ", " + quote(name7.trim()) + ", " + quote(name8.trim())
          		  + ", " + quote(name9.trim()) + ", " + quote(name10.trim())
          		  + ", " + quote(name11.trim()) + ", " + quote(name12.trim())
          		  + ", " + quote(name13.trim()) + ", " + quote(name14.trim())
          		  + ", " + quote(name15.trim()) + ", " + quote(name16.trim()));
          	//Close the output stream
        }
        else {
          log("Empty or invalid line. Unable to process.");
        }
        //no need to call scanner.close(), since the source is a String
      }
      
      // PRIVATE 
      private final File fFile;
      
      private static void log(Object aObject){
        System.out.println(String.valueOf(aObject));
      }
      
      private String quote(String aText){
        String QUOTE = "";
        return QUOTE + aText + QUOTE;
      }
    }
    Last edited by Prodigial Mouse; 01-20-2011 at 10:13 PM.

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,785
    Rep Power
    7

    Default

    Currently all the log method does is to display to standard output. If you want to write to a file then find yourself a good tutorial or maybe simply reading about classes such as File, FileWriter and other classes in the io package might get you started. Once you have made an attempt and written some code, come back with a specific question if you get stuck.

  3. #3
    Join Date
    Jan 2011
    Posts
    8
    Rep Power
    0

    Default

    So, I've got it now outputting data to a file, but it only saves the last line of data it executes on. This process is run upwards of 500,000 times and I'd like all the data to be caught and put into the specified .txt file

    Help on how to get more than one line of data copied over?

    Java Code:
      public final void processLineByLine() throws FileNotFoundException {
        //Note that FileReader is used, not File, since File is not Closeable
        Scanner scanner = new Scanner(new FileReader(fFile));
        try {
          //first use a Scanner to get each line
          while ( scanner.hasNextLine() ){
            processLine( scanner.nextLine() );
          }
        }
        finally {
          //ensure the underlying stream is always closed
          //this only has any effect if the item passed to the Scanner
          //constructor implements Closeable (which it does in this case).
          scanner.close();
        }
      }
      
      /** 
       Overridable method for processing lines in different ways.
        
       <P>This simple default implementation expects simple name-value pairs, separated by an 
       '=' sign. Examples of valid input : 
       <tt>height = 167cm</tt>
       <tt>mass =  65kg</tt>
       <tt>disposition =  "grumpy"</tt>
       <tt>this is the name = this is the value</tt>
      */
      protected void processLine(String aLine){
        //use a second Scanner to parse the content of each line 
        Scanner scanner = new Scanner(aLine);
        scanner.useDelimiter(",");
        if ( scanner.hasNext() ){
          String name = scanner.next();		//A
          String name1 = scanner.next();	//B
          String name2 = scanner.next();	//C
          String name3 = scanner.next();	//D
          String name4 = scanner.next();	//E
          String name5 = scanner.next();	//F
          String name6 = scanner.next();	//G
          String name7 = scanner.next();	//H
          String name8 = scanner.next();	//I
          String name9 = scanner.next();	//J
          String name10 = scanner.next();	//K
          String name11 = scanner.next();	//L
          String name12 = scanner.next();	//M
          String name13 = scanner.next();	//N
          String name14 = scanner.next();	//O
          String name15 = scanner.next();	//P
          String name16 = scanner.next();	//Q
          try {
    		java.io.FileWriter fileWriter = new java.io.FileWriter("C:/Documents and Settings/Owner/Desktop/Output.txt");
          	fileWriter.write("\n" + name.trim() + ", " + name1.trim() + ", " + name2.trim()
          		  + ", " + name3.trim() + ", " + name4.trim()
          		  + ", " + name5.trim() + ", " + name6.trim()
          		  + ", " + name7.trim() + ", " + name8.trim()
          		  + ", " + name9.trim() + ", " + name10.trim()
          		  + ", " + name11.trim() + ", " + name12.trim()
          		  + ", " + name13.trim() + ", " + name14.trim()
          		  + ", " + name15.trim() + ", " + name16.trim());
          	fileWriter.close();
          } catch (IOException e) {
      		// TODO Auto-generated catch block
      		e.printStackTrace();
      	}

  4. #4
    Join Date
    Jan 2011
    Posts
    8
    Rep Power
    0

    Default

    I figured it out, no thanks to anyone here.

  5. #5
    sunsnow86 is offline Member
    Join Date
    Jan 2011
    Posts
    2
    Rep Power
    0

    Default I also need to write output into a file,

    Here is my script, anyone can help me to write the output into a file, I will really appreciate!!!

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.util.zip.GZIPInputStream;



    public class Digest
    {
    private static final String CHROMOSOMES[]={
    "chr1","chr2","chr3",
    /* etc */
    "chrY"
    };
    private static class Enzyme
    {
    String name;
    String site;
    public Enzyme(String name,String site)
    {
    this.name=name;
    this.site=site.toUpperCase();
    }
    }
    //see NEW REBASE HOME
    private static final Enzyme ENZYMES[]=new Enzyme[]
    {
    new Enzyme("AatII","gacgtc"),
    new Enzyme("AbsI","cctcgagg"),
    new Enzyme("Acc65I","ggtacc"),
    /* (...) */
    new Enzyme("BamHI","ggatcc"),
    /* (...) */
    new Enzyme("EcoRI","gaattc"),
    /* (...) */
    new Enzyme("XmnI","gaannnnttc")
    };

    private static boolean compatible(char a,char b)
    {
    b=Character.toUpperCase(b);
    if("ATGC".indexOf(b)==-1) return false;
    switch(a)
    {
    case 'A': return b==a;
    case 'T': return b==a;
    case 'G': return b==a;
    case 'C': return b==a;


    case 'W': return "AT".indexOf(b)!=-1;
    case 'S': return "GC".indexOf(b)!=-1;
    case 'R': return "AG".indexOf(b)!=-1;
    case 'Y': return "CT".indexOf(b)!=-1;
    case 'M': return "AC".indexOf(b)!=-1;
    case 'K': return "GT".indexOf(b)!=-1;


    case 'B': return "CGT".indexOf(b)!=-1;
    case 'D': return "AGT".indexOf(b)!=-1;
    case 'H': return "ACT".indexOf(b)!=-1;
    case 'V': return "ACG".indexOf(b)!=-1;

    case 'N': return "ACGT".indexOf(b)!=-1;

    default: return false;
    }
    }



    public static void main(String[] args)
    {
    try
    {
    for(Enzyme enzyme:ENZYMES)
    {
    for(String chr:CHROMOSOMES)
    {
    URL url=new URL("http://hgdownload.cse.ucsc.edu/goldenPath/hg19/chromosomes/"+chr+".fa.gz");
    BufferedReader r=new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream())));
    int c;
    int genome_pos=0;
    int previous_pos=0;
    char buffer[]=new char[enzyme.site.length()];
    int buffer_length=0;
    while((c=r.read())!=-1)
    {
    if(c=='>')
    {
    while((c=r.read())!=-1 && c!='\n') { /* skip */}
    genome_pos=0;
    buffer_length=0;
    previous_pos=0;
    continue;
    }
    if(!Character.isLetter(c)) continue;
    buffer[buffer_length++]=(char)c;
    genome_pos++;

    if(buffer_length==buffer.length)
    {
    int i=0;
    for(i=0;i< buffer.length;++i)
    {
    if(!compatible(enzyme.site.charAt(i),buffer[i])) break;
    }
    if(i==buffer.length)
    {
    System.out.println(
    chr+"\t"+enzyme.name+"\t"+(previous_pos)+
    "\t"+(genome_pos-buffer.length)+
    "\t"+((genome_pos-buffer.length)-previous_pos)
    );
    previous_pos=genome_pos-buffer.length;
    }
    buffer_length--;
    System.arraycopy(buffer, 1, buffer, 0, buffer.length-1);
    }

    }
    r.close();
    System.out.println(
    chr+"\t"+enzyme.name+"\t"+(previous_pos)+
    "\t"+(genome_pos-buffer.length)+
    "\t"+((genome_pos-buffer.length)-previous_pos)
    );
    }
    }
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    }
    }

  6. #6
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    Kindly start your own thread and please use code tags.

  7. #7
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    I figured it out, no thanks to anyone here.
    Hello and welcome! You have a wonderful attitude that I'm sure will be of use to others who come here for help. You had clear concise questions and demonstrated a clear desire to participate in discussion involving your coding troubles. If only every poster here could be like you, I'm sure no one would bother reading this forum in the first place.

  8. #8
    Join Date
    Jan 2011
    Posts
    8
    Rep Power
    0

    Default

    Fuck you, I clearly explained my desires. Posted the entire source- and even continued to work on my problem without help.

    Get off your OT tower. Prick.

  9. #9
    Join Date
    Jan 2011
    Posts
    8
    Rep Power
    0

    Default

    Oh, and go ahead and ban me mr moderator ;D I won't be coming back- I've found a java savvy programmer amidst my old programming community.

  10. #10
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    You're a nice guy. Come over to my house for dinner sometime - I'll make you fresh pasta. Send me a private message for the address. :D

  11. #11
    Join Date
    Jan 2011
    Posts
    8
    Rep Power
    0

    Default

    Not only that, but to mr douchebag mcgee. No one invited me to participate in discussion, and my second question could have been easily answered. An explanation that when filewriter is being run in the context of the code I supplied; it deletes the preexisting file.

  12. #12
    Join Date
    Jan 2011
    Posts
    8
    Rep Power
    0

    Default

    Nah, my boyfriend is the only chef in mah life. Thanks for the offer though :O

  13. #13
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    You posted a question, and then posted a snotty "thanks to no one" message just 2.5 hours later. What do you expect? That people are being paid to sit around and wait for your questions so they can answer them immediately? People are here for the sole purpose of helping and being helped. Free. I can't believe someone would complain so quickly about not getting free advice fast enough.

    Secondly, your original post does not actually ask any questions at all. You mention vaguely what you want, and nothing else. You can't just post a huge code block and expect other people to read it line for line and fix all your bugs.

    This forum is about asking informed, specific questions or general conceptual questions about conceptual topics, not "I post it, you fix it". My sarcastic comment arose from you not giving the community a chance to respond, failing to make a good post Short, Self Contained, Correct Example and then being snotty to the community on top of it. This is the last I'm going to say, but I hope you will not let your anger prevent you from thinking about the points I made. Best of luck with your work, I hope you can come back and we can try again in the future. Cheers!

  14. #14
    Join Date
    Jan 2011
    Posts
    8
    Rep Power
    0

    Default

    Nah the comment and anger was directed at the ass who told me to consult a tutorial after i had previously said in my post that i'd tried multiple combinations to get it to work- and had openly admitted that i was referencing tutorials. It was the most worhtless statement ever.

  15. #15
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Alright, well, in that case please consider what I said, try to hold your anger here - this is a community for people who are ready willing and able to put in the time, and other than a bit of playful teasing, harsh language and 'yelling' aren't welcome.

    In your future posts, try to explain exactly what isn't working, what happens when it doesn't work (error messages) and short examples of the failing code. The community is very willing to help if you make it simple for them to do so. Good luck!

Similar Threads

  1. Replies: 2
    Last Post: 03-04-2011, 09:14 AM
  2. Replies: 6
    Last Post: 12-01-2010, 05:31 AM
  3. Outputting a * triangle
    By blackbeltsas in forum New To Java
    Replies: 1
    Last Post: 10-17-2010, 11:39 AM
  4. Data Sorting in a .data file using java
    By stutiger99 in forum New To Java
    Replies: 2
    Last Post: 10-08-2008, 02:52 AM
  5. Simple Addition Program Outputting Wrong Value
    By carlodelmundo in forum New To Java
    Replies: 4
    Last Post: 08-05-2008, 03:37 AM

Tags for this Thread

Posting Permissions

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