Saveindg a String in a .txt-File

Hello,
I want to save a String to a .txt-File, that is placed in a certain directory.
How can I Do that?
Tank you very much!
Greeting from cologne!
Marcel

      * Write text to a file.
     * @param text Text to write.
      * @param fileName Name of file to write to.
      * @throws IOException on error.
     static public void writeText(String text, String fileName) throws IOException {
        if (fileName != null && text != null) {
            BufferedWriter bw = null;
            try {
                bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "ISO-8859-1"));
                bw.write(text, 0, text.length());
            } finally {
                if (bw != null) { try { bw.close(); } catch (IOException ioe) { ioe.printStackTrace(System.err); }}
        }//else: input unavailable
    }//writeText()Please read D:\docs\JavaTutorial\essential\io\index.html

Similar Messages

  • How to read and write a string into a txt.file

    Hi, I am now using BEA Workshop for Weblogic Platform version10. I am using J2EE is my programming language. The problem I encounter is as the above title; how to read and write a string into a txt.file with a specific root directory? Do you have any sample codes to reference?
    I hope someone can answer my question as soon as possible
    Thank you very much.

    Accessing the file system directly from a web app is a bad idea for several reasons. See http://weblogs.java.net/blog/simongbrown/archive/2003/10/file_access_in.html for a great discussion of the topic.
    On Weblogic there seems to be two ways to access files. First, use a File T3 connector from the console. Second, use java.net.URL with the file: protocol. The T3File object has been deprecated and suggests:
    Deprecated in WebLogic Server 6.1. Use java.net.URL.openConnection() instead.
    Edited by: m0smith on Mar 12, 2008 5:18 PM

  • How do i search for a string in a txt file using java??

    How do i search for a string in a txt file using java??
    could you please help thanks
    J

    Regular expressinos work just fine, especially when
    searching for patterns. But they seem to be impying
    it's a specific group of characters they're looking
    for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.)

  • Comparing char in a string to strings in a txt file

    Hi guys, i am dveloping a scrabble application for a project in jvava. Currently, i am trying to work on coding a computer player to play against a human, ive finished all the game logic nd 2 human players can successfully play on the same system.
    My problem is when coming up with the AI logic, i am faced with the problem of how to compare the computer player's letters to the dictionary txt file in order to find the possible words he can play.
    For example, the PC player has the letters A,B,E,G,T,F in his rack, it searches the dictionary and finds words that also contain these characters, so it would return words like AT, BAT, GATE, etc. I have already looke up the Jumble algorithm, but i dont really understand it(im still quite new to java).
    I already have a ditionary class which i put the code below.
    What i want to do now is just to come up with a simple method that takes a string, and compares the chars, and find words that match the char and return them but i dont knw hw to come about it.
    import java.util.Scanner;      
    import java.io.IOException;  
    import java.util.ArrayList;   
    import java.io.*;             
    public class Dictionary
        ArrayList<String> dictionary;
        public Dictionary() throws IOException
            dictionary = new ArrayList<String>();
        public void readInDictionaryWords() throws IOException
            File dictionaryFile = new File("c:/data/dict.txt");    // declare the file
            if( ! dictionaryFile.exists()) {
                System.out.println("*** Error *** \n" +
                                   "Your dictionary file has the wrong name or is " +
                                   "in the wrong directory.  \n" +
                                   "Aborting program...\n\n");
                System.exit( -1);    // Terminate the program
            Scanner inputFile = new Scanner( dictionaryFile);
            while( inputFile.hasNext()) {
                dictionary.add( inputFile.nextLine().toUpperCase() );
        public boolean wordExists( String wordToLookup)
            if( dictionary.contains( wordToLookup)) {
                return true;    // words was found in dictionary
            else {
                return false;   // word was not found in dictionary
        return"";
    }

    Loops...
    You take the first
    then second
    then third
    and etc
    You take the first 2
    the next 2
    the next 2
    etc
    all the way through n characters
    once you have gone through this, then you have to do all possible combinations of characters of 2 through n.
    Here is an implementation of N choose k for k up to 7:
    public class Junk {
      public Junk(){
      public void choose1(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          System.out.println("("+s.charAt(i)+")");
          lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose2(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
              System.out.println("("+s.charAt(i)+", "+s.charAt(j)+")");
              lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose3(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+")");
              lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose4(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              for(int l=k+1; l<s.length(); l++){
                System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+")");
                lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose5(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              for(int l=k+1; l<s.length(); l++){
                for(int m=l+1; m<s.length(); m++){
                  System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+")");
                  lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose6(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              for(int l=k+1; l<s.length(); l++){
                for(int m=l+1; m<s.length(); m++){
                  for(int n=m+1;n<s.length(); n++){
                    System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+", "+s.charAt(n)+")");
                    lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public void choose7(String s){
        int lCount=0;
        for(int i=0; i<s.length(); i++){
          for(int j=i+1; j<s.length(); j++){
            for(int k=j+1; k<s.length(); k++){
              for(int l=k+1; l<s.length(); l++){
                for(int m=l+1; m<s.length(); m++){
                  for(int n=m+1; n<s.length(); n++){
                    for(int o=n+1; o<s.length(); o++){
                      System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+", "+s.charAt(n)+", "+s.charAt(o)+")");
                      lCount++;
        System.out.println("Distinct Combinations: "+lCount);
      public static void main(String[] args) {
        Junk j = new Junk();
        j.choose7("1234567");
    }I'll leave it to you to integerate the algos into your app appropriately.

  • Searching for strings in a txt file

    I am writing a program based on the six degrees of seperation theory.
    Basically I have been given a (very large) txt file from the imdb with a list of all the films written in it.
    The text in the document is written like this:
    'Tis Autumn: The Search for Jackie Paris (2006)/Paris, Jackie/Moody, James (IV)/Bogdanovich, Peter/Vera, Billy/Ellison, Harlan/Newman, Barry/Whaley, Frank/Murphy, Mark (X)/Tosches, Nick (I)/Moss, Anne Marie
    (Desire) (2006)/Ruggieri, Elio/Micijevic, Irena
    .45 (2006)/Dorff, Stephen/Laresca, Vincent/Eddis, Tim/Bergschneider, Conrad/Campbell, Shawn (II)/Macfadyen, Angus/John, Suresh/Munch, Tony/Tyler, Aisha/Augustson, Nola/Greenhalgh, Dawn/Strange, Sarah/Jovovich, Milla/Hawtrey, Kay
    10 Items or Less (2006)/Ruiz, Hector Atreyu/Torres, Emiliano (II)/Parsons, Jim (II)/Freeman, Morgan (I)/Pallana, Kumar/Cannavale, Bobby/Nam, Leonardo/Hill, Jonah/Vega, Paz/Echols, Jennifer/Dudek, Anne/Berardi, Alexandra
    10 MPH (2006)/Weeks, Hunter/Armstrong, Pat (II)/Caldwell, Josh/Waisman, Alon/Keough, Johnathan F./Weeks, Gannon
    10 Tricks (2006)/Cruz, Raymond/Swetland, Paul/Selznick, Albie/Hennings, Sam/Gleason, Richard/Leake, Damien/Skipp, Beth/Ishibashi, Brittany/Thompson, Lea (I)/Jinaro, Jossara/Brink, Molly
    1001 Nights (2006)/Wright, Jeffrey (I)
    10th & Wolf (2006)/Lee, Tommy (VI)/Renfro, Brad/Ligato, Johnny/De Laurentiis, Igor/Luke Jr., Tony/Mihok, Dash/Garito, Ken/Capodice, John/Dennehy, Brian/Gullion, Jesse/Salvi, Francesco (I)/Cordek, Frank/Marsden, James (I)/Bernard, Aaron/Brennan, Patrick (VII)/O'Rourke, Ben/Gallo, Billy/Heaphy, James/Stragand, Dave/Vellozzi, Sonny/Pistone, Joe (I)/Morse, David (III)/Landis, Pete/Cain, Atticus/Trevelino, Dan/Demme, Larry/Sisto, Frank/Rosenbaum, Paul/Grimaldi, James (I)/Ribisi, Giovanni/Hopper, Dennis/Devon, Tony/Sigismondi, Barry/Kilmer, Val/Marinelli, Sonny/Cacia, Joseph/Rossi, Leo (II)/Tott, Jeffrey/Wawrzyniak, Aaron/Boombotze, Joey/Marie, Corina/Arvie, Michilline/Warren, Lesley Ann/De Laurentiis, Veronica/Moresco, Amanda/Boecker, Margot/Rossi, Rose/Latimore, Meritt/Dunlap, Doreen/Perabo, Piper/Horrell, Nickole/Sonnichsen, Ingrid
    11 Minutes Ago (2006)/Irving, Len/Welzbacher, Craig/Michaels, Ian/Dahl, Evan Lee/Gebert, Bob/Juuso, Jeremy/Hope, Trip/Green-Gaber, Renata/Dawn, Turiya/Reneau, Taryn/M
    Thats just 2 lines!
    what the program will do is take in a name (from a gui) of an actor/actress and find the smallest connection to a famous actor.
    So first things first, my idea of thinking is to search the file for K.E.V.I.N. B.A.C.O.N and all his films, and safe them into an array. Then do another search for films from the actor that the user entered at the gui. then find the shortest possible connection to both stars.
    my code for the search part of the program
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.File;
    import java.io.FileNotFoundException;
    public class FileSearch {
         File aFile = new File("cast.06.txt");     
         FileInputStream inFile = null;
         String actor = "surname, forename"; // the person who will be the centre point e.g. kevin.bacon.
           //get the result of the actor from the gui will go here.
         public void openFilm()
              try
                  inFile = new FileInputStream(aFile);     
              catch(FileNotFoundException e)
                   System.out.println("Error");
    }The problem I have is that I can't work out how to search the txt file for a specific string/s and save them into an array. (I'm not sure if this is the best way to go about it or not at this stage).
    So whats the best way to search for an actor from that file and save the film title and the year of release?
    Hope this makes sense? what I hope the final program will be like is like this http://oracleofbacon.org/

    I went away and looked at regular expressions and this is what I came up with
    public class NameSearch{
         public static void main(String[] args)
              NameSearch ns = new NameSearch();
              ns.runIt();
         public void runIt()
              java.util.Scanner fileScan = null;
              try{
                   fileScan = new java.util.Scanner(new java.io.File("imdb.txt"));
              }catch(java.io.FileNotFoundException e)
                   e.printStackTrace();
                   System.exit(0);
              String token = null;
              String actor = "Surname, Forename";
    //real name will go in actor, left it like that for example
              while(fileScan.hasNext()){
                   token = fileScan.next();
                   Pattern pattern = Pattern.compile(actor);
                   Matcher m = pattern.matcher(token);
                   while(m.find())
                        System.out.println(m.start() + m.end());
    }This by any means not finished, I'm just trying to get to grips with regualr expressions. But when I run the program it doesn't return anything, from what I've tried to work out is it should return actor x amount of times they appear in the file. But when I run it nothing comes back (the actors name is in the text file) so I'm not too sure what I'm doing wrong, any suggestion please

  • Replace the text numbers string in a txt file using C++.. Help Me..

    Read a Document and replace the text numbers in a txt file using c++..
    For ex: 
    Before Document: 
    hai hello my daily salary is two thousand and five and your salary is five billion. my age is 
    twenty-five. 
    After Document: 
    hai hello my daily salary is # and your salary is #. my age is #. 
    All the text numbers and i put the # symbol.. 
    I am trying this code: 
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    ifstream myfile_in ("input.txt");
    ofstream myfile_out ("output.txt");
    string line;
    void find_and_replace( string &source, string find, string replace ) {
    size_t j;
    for ( ; (j = source.find( find )) != string::npos ; ) {
    source.replace( j, find.length(), replace );
    myfile_out << source <<endl;
    cout << source << endl;
    int main () {
    if (myfile_in.is_open())
    int i = 0,j;
    //string strcomma ;
    // string strspace ;
    while (! myfile_in.eof() )
    getline (myfile_in,line);
    string strcomma= "two";
    string strspace = "#";
    find_and_replace( line , strcomma , strspace );
    i++;
    myfile_in.close();
    else cout << "Unable to open file(s) ";
    system("PAUSE");
    return 0;
    Please help me.. Give me the correct code..

    Open the file as a RandomAccessFile. Check its length. Declare a byte array as big as its length and do a single read to get the file into RAM.
    Is this a simple text file (bytes)? No problem. If it's really 16-bit chars, use java.nio to first wrap the byte array as a ByteBuffer and then view the ByteBuffer as a CharBuffer.
    Then you're ready for search/replace. Do it as you would in any other language. Be sure to use System.arraycopy() to shove your bytes right (replace bigger than search) or left (replace smaller than search).
    When done, a single write() to the RandomAccessFile will put it all back. As you search/replace, keep track of size. If the final file is smaller than the original, use a setLength() to the new size to avoid extraneous data at the end.

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • Enquiry on converting a *.txt file to a *.pdf file

    Enquiry on converting a *.txt file to a *.pdf file
    Aim of this software: Let the user to choose a *.txt file to convert it to a *.pdf file.
    1. User clicks a choose file button. [chooseFileButton]
    2. User clicks the Export 2 button [exportButton2]
    3. User clicks the Text -> PDF button [pdfConverterButton]
    After choosing the file and click the choose file button:
    System prints out (for debbuging use...)
    ---------------------------Print from Trans.java - method transMemory--------------------
    File's name: file.txt
    File's path: C:\Users\charles\Desktop\netbean\Pdfproject1\file.txt
    After clicking the Export 2 button, system prints out:
    ---------------Print out the File's name - from DataOut.java - getData() Method-------------------------
    File's Name: file.txt
    ----------------Print out the file's path - from DataOut.java - getData() Method--------------
    File's path: C:\Users\charles\Desktop\netbean\Pdfproject1\file.txt
    The file now being read by the system: transNameData.txt
    The data being copied to this file: copyOfFileName.txt Destination
    This file has been copied: file.txt Original
    The following content has been copied:
    ---start of content - from TheFile.java - save2() method---
    Some content.....................................
    --------end of content--------
    Jul 18, 2010 3:32:04 PM mainFrame1 exportButton2ActionPerformed
    SEVERE: null
    java.io.IOException: Permission denied
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:199)
    at java.io.DataInputStream.read(DataInputStream.java:132)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at TheFile.save2(TheFile.java:144)
    at mainFrame1.exportButton2ActionPerformed(mainFrame1.java:168)
    at mainFrame1.access$200(mainFrame1.java:30)
    at mainFrame1$3.actionPerformed(mainFrame1.java:79)
    at java.awt.Button.processActionEvent(Button.java:392)
    at java.awt.Button.processEvent(Button.java:360)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    After clicking the text -> PDF button, system prints out:
    The following data is called by the PDF converter button...
    ---------------Print out the File's name - from DataOut.java - getData() Method-------------------------
    File's Name: file.txt
    ----------------Print out the file's path - from DataOut.java - getData() Method--------------
    File's path: C:\Users\charles\Desktop\netbean\Pdfproject1\file.txt
    MakePdf.java is loading... - createPdf() method
    File you have chosen and this file will be converted to a PDF file: file.txt
    And the content of the file is:
    ---start of content--- (Info from MakePdf.java)
    Some content.....................................
    ---end of content---
    Print out the content again: Some content..................................... ---> Info from SubClass DocToPdf of MakePdf.java
    Exception in thread "AWT-EventQueue-0" ExceptionConverter: java.io.IOException: The document has no pages.
    at com.lowagie.text.pdf.PdfPages.writePageTree(Unknown Source)
    at com.lowagie.text.pdf.PdfWriter.close(Unknown Source)
    at com.lowagie.text.pdf.PdfDocument.close(Unknown Source)
    at com.lowagie.text.Document.close(Unknown Source)
    at MakePdf$DocToPdf.createDoc(MakePdf.java:140)
    at MakePdf.createPdf(MakePdf.java:97)
    at TheFile.forPdfUse(TheFile.java:267)
    at mainFrame1.pdfConverterButtonActionPerformed(mainFrame1.java:184)
    at mainFrame1.access$300(mainFrame1.java:30)
    at mainFrame1$4.actionPerformed(mainFrame1.java:86)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6263)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    at java.awt.Component.processEvent(Component.java:6028)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.java:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2478)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    BUILD SUCCESSFUL (total time: 1 minute 41 seconds)

    Source code: MakePdf.java
    import com.lowagie.text.DocumentException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import java.lang.String;
    import java.io.*;
    public class TheFile {
    String pathData;
    String nameData;
         public void PrepareJFileChooserData2(){
            try {
                // Create a object for JFileChooser.
                final JFileChooser choose = new JFileChooser();
                choose.showOpenDialog(null);
                File file = new File(choose.getSelectedFile(), "");
                pathData = file.getPath(); //get the path of the chosen file
                nameData = file.getName(); //get the name of the chosen file
                //Try to copy file to a temp file.
                Cfile2 cfile = new Cfile2();
                cfile.writeFile(nameData); // write nameData into the temp.txt file.
                //return pathData;
            } catch (IOException ex) {
                Logger.getLogger(TheFile.class.getName()).log(Level.SEVERE, null, ex);
          public String getPathName(){
                return pathData;
          public String getNameData(){
              return nameData;
        public class Cfile2{
        public void writeFile(String fName) throws IOException {
            PrintWriter pr = new PrintWriter(new File("temp.txt"));
            pr.println();
            pr.print("\n");
            pr.write("-------------------From SubClass - Cfile2 in TheFile.java----------------------");
            pr.write("File Name: " +nameData); // write the value of nameData to temp.txt
            pr.print("\n");
            pr.write("File's Path: "+pathData); // write the value of pathData to temp.txt
            pr.print("\n");
            pr.print("-------------------------------------------------------------------------------");
            pr.flush();  // Flush the data.
            pr.close();  // Close to unlock and flush to disk.
        public void save2() throws FileNotFoundException, IOException{
           // Copy and print out the file's name only
           String fileName = "transNameData.txt";
           File originFile = new File(fileName); //open the file to read
           System.out.println("The file now being read by the system: " +originFile);  //originFile = transNameData.txt
           File destinationFile = new File("copyOfFileName.txt"); // open another file and prepare to write in
        try {
            //Start trying to write data to file - copyOfFileName.txt
          byte[] readData = new byte[2048];
          FileInputStream fis = new FileInputStream(new File(fileName)); // Seems it writes the value of transNameData.txt to copy.txt
          int count = fis.available();
          if(count>0){
          FileOutputStream fos = new FileOutputStream(destinationFile);
          int i = fis.read(readData);
          while (i != -1) {
            fos.write(readData, 0, i);
            i = fis.read(readData);
          System.out.println("The data being copied to this file: " +destinationFile+ " Destination");
          fos.flush();
          fos.close();
          fis.close();
            }else{
              System.out.print("Error");
        } catch (IOException e) {
          System.out.println(e);
        // Copy the content of the file only
        FileInputStream fstream = new FileInputStream("transNameData.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          System.out.println ("This file has been copied: " +strLine+ " Original"); //Work successfully, strLine has the value [file's title]
          File newDestinationFile = new File("ContentCopy.txt"); //Open the newCopy.txt file
          byte[] newReadData = new byte[2048];
          FileInputStream newFileInputStream = new FileInputStream(new File(strLine)); // See whether it can write it in... ok done!
          //String newString = newReadData.toString();
          //System.out.print("Content that has been copied: " +newString); //It prints out data in byte form...?!
          FileOutputStream newFileOutputStream = new FileOutputStream(newDestinationFile);
          int i = newFileInputStream.read(newReadData);
          while (i != -1) {
            newFileOutputStream.write(newReadData, 0, i);
            i = newFileInputStream.read(newReadData);
        FileInputStream newfstream = new FileInputStream(strLine);
        // Get the object of DataInputStream
        DataInputStream newin = new DataInputStream(newfstream);
            BufferedReader newbr = new BufferedReader(new InputStreamReader(newin));
        String content;
        //Read File Line By Line
        while ((content = newbr.readLine()) != null)   {
          // Print the content on the console
            System.out.println("\n");
            System.out.println("The following content has been copied: ");
            System.out.println(" ");
            System.out.println("---start of content - from TheFile.java - save2() method---");
            System.out.println(" ");
            System.out.println(content);
            System.out.println(" ");
            System.out.println("--------end of content--------");
        //Close the input stream
        in.close();
        //Close the input stream
        in.close();
    //----------- start PDF parser  ---> to txt format -------
       public void pdf() throws FileNotFoundException, IOException{
        //-----again--
       FileInputStream inStream = new FileInputStream("transNameData.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(inStream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          System.out.println ("Watch out: " +strLine+ "  ---> It should be printed successfully!!"); //Work successfully
        //---again......
        PDFTextParser pdftextparser = new PDFTextParser();
        pdftextparser.pdftoText(strLine);
        public void forPdfUse() throws FileNotFoundException, IOException, DocumentException{
            MakePdf makePdf = new MakePdf();
            makePdf.createPdf();
    }

  • A better way to search a string in a 3GB txt file

    I am looking for a string(12 characters) in a 3GB txt file. I use the file reader to go though each line and use the startwith() (that 12 characters are from the beginning of each line) to check if that line contain the string I am searching for. Is there a faster way to do it? Thank's.

    I would avoid using java to parse/search a 3 GB text file at all costs. Any java solution is going to have terrible performance and you may run into memory problems. I would recomend that you either a) develop a native method for resolving this search and just invoke it from your current java class or b) use Runtime.exec to invoke a native OS command for searching the file (like grep or find) and parse the results. ....
    I'm not even sure how I would complete that task with java exclusivly ... maybe break the file into smaller parts, then iterate through each smaller, temporary file ... I would really recomend storing your data in a different format if possible. A 3 GB text file just isn't very partical or secure.
    ... oh, to answer your original question (which I'm not sure if I all ready did), the fatest way to load the file is to wrap it into some BufferedReader. The fatest way to perform String searches is through the java.util.regex package if you have access to the 1.4 API. Other wise, just use basic String searches, as you all ready are.

  • Script to search all files in specified folder for multiple string text values listed in a source file and output each match to one single results txt file

    I have been searching high and low for this one.  I have a vbscript that can successfully perform the function if one file is listed.  It does a Wscript.echo on the results and if I run this via command using cscript, I can output to a text file
    that way.  However, I cannot seem to get it to work properly if I want it to search ALL the files in the folder.  At one point, I was able to have it create the output file and appear as if it worked, but it never showed any results when the script
    was executed and folder was scanned.  So I am going back to the drawing board and starting from the beginning.
    I also have a txt file that contains the list of string text entries I would like it to search for.  Just for testing, I placed 4 lines of sample text and one single matching text in various target files and nothing comes back.  The current script
    I use for each file has been executed with a few hundred string text lines I want it to search against to well over one thousand.  It might take awhile, but it works every time. The purpose is to let this run against various log files in a folder and
    let it search.  There is no deleting, moving, changing of either the target folder/files to run against, nor of the file that contains the strings to search for.  It is a search (read) only function, going thru the entire contents of the folder and
    when done, performs the loop function and onto the next file to repeat the process until all files are searched.  When completed, instead of running a cscript to execute the script and outputting the results to text, I am trying to create that as part
    of the overall script.  Saving yet another step for me to do.
    My current script is set to append to the same results file and will echo [name of file I am searching]:  No errors found.  Otherwise, the
    output shows the filename and the string text that matched.  Because the results append to it, I can only run the script against each file separately or create individual output names.  I would rather not do that if I could include it all in one.
     This would also free me from babysitting it and running each file script separately upon the other's completion.  I can continue with my job and come back later and view the completed report all in one.  So
    if I could perform this on an entire folder, then I would want the entries to include the filename, the line number that the match occurred on in that file and the string text that was matched (each occurrence).  I don't want the entire line to be listed
    where the error was, just the match itself.
    Example:  (In the event this doesn't display correctly below, each match, it's corresponding filename and line number all go together on the same line.  It somehow posted the example jumbled when I listed it) 
    File1.txt Line 54 
    Job terminated unexpectedly
     File1.txt Line 58 Process not completed
    File1.txt
    Line 101 User input not provided
    File1.txt
    Line 105  Process not completed
    File2.txt
    No errors found
    File3.txt
    Line 35 No tape media found
    File3.txt
    Line 156 Bad surface media
    File3.txt Line 188
    Process terminated
    Those are just random fake examples for this post.
    This allows me to perform analysis on a set of files for various projects I am doing.  Later on, when the entire search is completed, I can go back to the results file and look and see what files had items I wish to follow up on.  Therefore, the
    line number that each match was found on will allow me to see the big picture of what was going on when the entry was logged.
    I actually import the results file into a spreadsheet, where further information is stored regarding each individual text string I am using.  Very useful.
    If you know how I can successfully achieve this in one script, please share.  I have seen plenty of posts out there where people have requested all different aspects of it, but I have yet to see it all put together in one and work successfully.
    Thanks for helping.

    I'm sorry.  I was so consumed in locating the issue that I completely overlooked posting what exactly I was needing  help with.   I did have one created, but I came across one that seemed more organized than what I originally created.  Later
    on I would learn that I had an error in log location on my original script and therefore thought it wasn't working properly.  Now that I am thinking that I am pretty close to achieving what I want with this one, I am just going to stick with it.
    However, I could still use help on it.  I am not sure what I did not set correctly or perhaps overlooking as a typing error that my very last line of this throws an "Expected Statement" error.  If I end with End, then it still gives same
    results.
    So to give credit where I located this:
    http://vbscriptwmi.uw.hu/ch12lev1sec7.html
    I then adjusted it for what I was doing.
    What this does does is it searches thru log files in a directory you specify when prompted.  It looks for words that are contained in another file; objFile2, and outputs the results of all matching words in each of those log files to another file:  errors.log
    Once all files are scanned to the end, the objects are closed and then a message is echoed letting you know (whether there errors found or not), so you know the script has been completed.
    What I had hoped to achieve was an output to the errors.log (when matches were found) the file name, the line number that match was located on in that file and what was the actual string text (not the whole line) that matched.  That way, I can go directly
    to each instance for particular events if further analysis is needed later on.
    So I could use help on what statement should I be closing this with.  What event, events or error did I overlook that I keep getting prompted for that.  Any help would be appreciated.
    Option Explicit
    'Prompt user for the log file they want to search
    Dim varLogPath
    varLogPath = InputBox("Enter the complete path of the logs folder.")
    'Create filesystem object
    Dim oFSO
    Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")
    'Creates the output file that will contain errors found during search
    Dim oTSOut
    Set oTSOut = oFSO.CreateTextFile("c:\Scripts\errors.log")
    'Loop through each file in the folder
    Dim oFile, varFoundNone
    VarFoundNone = True
    For Each oFile In oFSO.GetFolder(varLogPath).Files
        'Verifies files scanned are log files
        If LCase(Right(oFile.Name,3)) = "log" Then
            'Open the log file
            Dim oTS
            oTS = oFSO.OpenTextFile(oFile.Path)
            'Sets the file log that contains error list to look for
            Dim oFile2
            Set oFile2 = oFSO.OpenTextFile("c:\Scripts\livescan\lserrors.txt", ForReading)
            'Begin reading each line of the textstream
            Dim varLine
            Do Until oTS.AtEndOfStream
                varLine = oTS.ReadLine
                Set objRegEx = CreateObject("VBScript.RegExp")
                objRegEx.Global = True  
                Dim colMatches, strName, strText
                Do Until oErrors.AtEndOfStream
                    strName = oFile2.ReadLine
                    objRegEx.Pattern = ".{0,}" & strName & ".{0,}\n"
                    Set colMatches = objRegEx.Execute(varLine)  
                    If colMatches.Count > 0 Then
                        For Each strMatch in colMatches 
                            strText = strText & strMatch.Value
                            WScript.Echo "Errors found."
                            oTSOut.WriteLine oFile.Name, varLine.Line, varLine
                            VarFoundNone = False
                        Next
                    End If
                Loop
                oTS.Close
                oFile2.Close
                oTSOut.Close
                Exit Do
                If VarFoundNone = True Then
                    WScript.Echo "No errors found."
                Else
                    WScript.Echo "Errors found.  Check logfile for more info."
                End If
        End if

  • How to search a special string in txt file and return it's position in txt file?

    How to search a special string in txt file and return it's position in txt file?

    I just posted a solution for a similar question here:  http://forums.ni.com/ni/board/message?board.id=170​&view=by_date_ascending&message.id=362699#M362699
    The top portion can search for the location of a string, while the bottom portion is to locate the position of a character.  Both can search for a character.
    The position of the character within the file is displayed in the indicator(s).
    R

  • [CS3 JS]  Reading TXT file content into String

    Hello,
    I'm currently wanting to display a dialog box that has a dropdown menu containing all countries of the world.
    I have an external txt file that contains a list of all countries.
    I thought I would simply read-in the contents of the 'txt' file into a string and use it for displaying the list.
    For example
    i Instead of the usual:
    > var myLandMenu = dropdowns.add({stringList:["A", "B"...], selectedIndex:0});
    i I thought of doing something like:
    > var myLandList = ....? HELP ?....
    > var myLandMenu = dropdowns.add({stringList:myLandList, selectedIndex:0});
    Is this the way to do it?
    What would be the way to read in the text file content as a string?
    Thanks in advance,
    Lee

    > var myLandList = ....? HELP ?....
    > var myLandMenu = dropdowns.add({stringList:myLandList, selectedIndex:0});
    It's hard to tell from context, but myLandList needs to be an array of strings.
    If the file has one element per line, this would be one way of handling the
    conversion:
    var file = File("~/countries.txt");
    file.open("r");
    var str = file.read();
    file.close();
    var myLandList = str.split(/[\r\n]+/);
    And assuming that this is ScriptUI and not the older ID UI, the menu creation
    would look more like:
    var myLandMenu = dropdowns.add(bounds, myLandList);
    myLandMenu.items[0].selected = true;
    -X
    for photoshop scripting solutions of all sorts
    contact: [email protected]

  • Remove string from txt file

    Hello guys,
    I need some help. I have to remove some content of Tolerance "column" (see attach). The string which I wish to remove is "+/- 0s" and replace it with an empty string. I need to remove this for each row where "+/- 0s" appears.  
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    sample.txt ‏3 KB

    Hi Samoth,
    I dont know if I understood your requirement properly, but please check the attached snippet if it helps.
    If this does not satisfy your requirement, then please give some more details.
    Attachments:
    Remove string from txt file.png ‏21 KB

  • Urgent: deleting a specific string form an existing .txt file

    Plz help me with a sample code on how to delete a specific string form an existing .txt file..it is very urgent...
    thanks in advance

    String path = "D:\\text.txt";
    File file = new File(path);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = "";
    String text = "";
    while((line = br.readLine()) != null) {
    text += line + "\n";
    br.close();
    String textToFind = "find";
    int start = text.indexOf(textToFind);
    if(start != -1) {
    text = text.substring(0, start) + text.substring(start + textToFind.length());
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write(text, 0, text.length());
    bw.close();
    }

  • How to recognize string in txt file and set it as variable

    Hi, 
    I have txt file and somwhere in it string starting with:
    data directory....:
    How (using batch file) find it in the text, read and set the value as a variable? I mean the string is:
    data directory....: c:\datadir
    where what I mean value is  in this case "c:\datadir". So I want batch file to read the txt file, find string starting with "data directory....:" and then set "c:\datadir" as a variable. 
    Best, mac

    It's not very intuitive to do this sort of thing in a batch file. If you have the option to use PowerShell instead, I'd highly recommend it. It's the new way for performing command-line tasks in Windows, and there's no need to struggle with the old command
    prompt anymore.
    Here are PowerShell and batch examples of doing this type of string parsing:
    # PowerShell:
    $dataDirectory = Get-Content .\test.txt |
    ForEach-Object {
    if ($_ -match '^\s*data directory\.*:\s*(.+?)\s*$')
    $matches[1]
    break
    $dataDirectory
    # Batch file:
    @echo off
    setlocal EnableDelayedExpansion
    set DATA_DIRECTORY=
    for /F "tokens=1,* delims=:" %%a in (test.txt) do (
    set PROPERTY=%%a
    set PROPERTY=!PROPERTY:~0,14!
    if /I "!PROPERTY!" equ "data directory" (
    set DATA_DIRECTORY=%%b
    :RemovingSpaces
    if "%DATA_DIRECTORY:~0,1%" neq " " goto :SpacesRemoved
    set DATA_DIRECTORY=%DATA_DIRECTORY:~1%
    goto :RemovingSpaces
    :SpacesRemoved
    echo %DATA_DIRECTORY%
    endlocal

Maybe you are looking for