Reading text file, Replace string, Write to new file....

I'm kind a lost of on this problem. Using the BufferedReader class and BufferedWriter class, develop an application that reads lines of text from a file. Replace any occurrence of the word *?the?* with *?JAVAJAVA?* and change all characters to upper case before writing each line to a different text file named outfile.txt. Finally, have your application use the appropriate method on the File class to return the absolute path of the outfile.txt file and output the path to the screen.
* Created December 10, 2008
* @author Fausto Rivera
* Colorado Technical University - Online Campus
* IT271-0804B-02 Intermediate Object Oriented Programming II
* Phase 2 IP
* Instructor: Cheryl B Frederick
import java.io.File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FRiveraReader {
      public static void main(String[] args) {
      // instantiated a new application object to initialize the application
      FRiveraReader application = new FRiveraReader();}
//      application.getReadfr();  // call to openFile method
//      application.doWritefr(); // call to readRecords method
//      application.closeFile();  // call to closeFile method
public FRiveraReader(){}
  public void getReadfr (String friveraInfile, String fr []){
   int i;
   File fileName = makeAbsoluteFilename(friveraInfile);
   try{
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line = reader.readLine();
     i=0;
      while (line != null) {
       fr[i] =line;
       line = reader.readLine();
    i++;
  reader.close();
catch(IOException e) {
System.out.println("Error with reading file:" + friveraInfile);
}//end of getOrder method
public void doWritefr(String friveraOutfile, String fw[]){//String name of file, String array to be written
int i;
File fileNameout = makeAbsoluteFilename(friveraOutfile);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter (fileNameout));
  i=0;
  while (fw[i] != null) {
   writer.write(fw[i] + "%n"); //need delimiters between data in file;also, reader reads a line
   i++;
  writer.close();
catch(FileNotFoundException e) {
System.out.println("File not found");
catch(IOException e) {
System.out.println("Error with reading file:" + friveraOutfile);
}//end of getOrder method
private File makeAbsoluteFilename(String friveraOutfile)//these 2 classes used to resolve file name
        File file = new File(friveraOutfile);
        if(!file.isAbsolute()) {
            file = new File(friveraOutfile);
        return file;

I have modified my code as far as being able to create a text file, write to string, and change to upper case. Now, how can I connected input to the output stream and then replace all the instances of the string "the" for the string "JAVAJAVA"? When the file is created, it goes into a loop writing the following:
nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%
Here is my modified code
import java.io.File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FRiveraReader {
public FRiveraReader() {}
private static final String inFile = "C:\\Documents and Settings\\Fausto Rivera\\My Documents\\NetBeansProjects\\Rivera_F_IT271_0804B_02_PH2_IP\\friverainfile.txt";//the path name of your file
  public void myReadfr (){
   try {
    BufferedReader reader = new BufferedReader(new FileReader(inFile));
    //String "JAVAJAVA" = String "the";
    System.out.println(inFile);
    String line = reader.readLine();
      while (reader != null) {
       line = reader.readLine();
  reader.close();
catch(IOException e) {
System.out.println("Error with reading file:" + inFile);
}//end of myReadfr method
public void myWritefr(){//String name of file, String array to be written
File outFile = new File ("C:\\Documents and Settings\\Fausto Rivera\\My Documents\\NetBeansProjects\\Rivera_F_IT271_0804B_02_PH2_IP\\myoutFile.txt");
try {
BufferedWriter writer = new BufferedWriter(new FileWriter (outFile));
String newline = writer.toString() .toUpperCase();
  while (writer != null) {
   writer.write(newline + "%n"); //need delimiters between data in file;also, reader reads a line
  writer.close();
catch(FileNotFoundException e) {
System.out.println("File not found");
catch(IOException e) {
System.out.println("Error writing file:" + outFile);
}//end of getOrder method
private File makeAbsoluteFilename(String myoutFile)//these 2 classes used to resolve file name
        File file = new File(myoutFile);
        if(!file.isAbsolute()) {
            file = new File(myoutFile);
        return file;
  }Edited by: FRiveraJr on Dec 17, 2008 12:10 PM

Similar Messages

  • Replace string in ms word file

    Salue,
    I need to add a functionality to my Java app by allowing the replacement of strings in ms word files.
    Basically I need to use an original MS Word file as template and then populate it with data,
    replacing some keywords. And I need to do this with Java.
    I know MS Word is binary and not text file, so I was wondering if there is any Java API to let me do this?
    Merci, Irene

    Irene,
    It is possible to use ms word(.doc) or openoffice(.odt) templates and populate them with data.
    I came across this solution while trying to convert to pdf, but it is usefull in replacing also.
    import officetools.OfficeFile; // officetools.jar from this website http://www.dancrintea.ro/doc-to-pdf/
    FileInputStream fis = new FileInputStream(new File("your_template.doc"));
    FileOutputStream fos = new FileOutputStream(new File("your_final_result.doc"));
    OfficeFile f = new OfficeFile(fis,"localhost","8100", true);
    *f.replaceAll("hello","salue :) ");*
    f.write(fos);

  • How can I read, millions of records and write as *.csv file

    I have to return some set of columns values(based on current date) from the database (could be million of record also) The dbms_output can accomodate only 20000 records. (I am retrieving thru a procedure using cursor).
    I should write these values to a file with extn .csv (comma separated file) I thought of using a utl_file. But I heard there is some restriction on the number of records even in utl_file.
    If so, what is the restriction. Is there any other way I can achive it? (BLOB or CLOB ??).
    Please help me in solving this problem.
    I have to write to .csv file, the values from the cursor I have concatinated with "," and now its returning the value to the screen (using dbms_output, temporarily) I have to redirect the output to .csv
    and the .csv should be in some physical directory and I have to upload(ftp) the file from the directory to the website.
    Please help me out.

    Jimmy,
    Make sure that utl_file is properly installed, make sure that the utl_file_dir parameter is set in the init.ora file and that the database has been re-started so that it will take effect, make sure that you have sufficient privileges granted directly, not through roles, including privileges to the file and directory that you are trying to write to, add the exception block below to your procedure to narrow down the source of the exception, then test again. If you still get an error, please post a cut and paste of the exact code that you run and any messages that you received.
    exception
        when utl_file.invalid_path then
            raise_application_error(-20001,
           'INVALID_PATH: File location or filename was invalid.');
        when utl_file.invalid_mode then
            raise_application_error(-20002,
          'INVALID_MODE: The open_mode parameter in FOPEN was
           invalid.');
        when utl_file.invalid_filehandle then
            raise_application_error(-20002,
            'INVALID_FILEHANDLE: The file handle was invalid.');
        when utl_file.invalid_operation then
            raise_application_error(-20003,
           'INVALID_OPERATION: The file could not be opened or
            operated on as requested.');
        when utl_file.read_error then
            raise_application_error(-20004,
           'READ_ERROR: An operating system error occurred during
            the read operation.');
        when utl_file.write_error then
            raise_application_error(-20005,
                'WRITE_ERROR: An operating system error occurred
                 during the write operation.');
        when utl_file.internal_error then
            raise_application_error(-20006,
                'INTERNAL_ERROR: An unspecified error in PL/SQL.');

  • Quickie: Write to measurement file VI, how to create new file?

    I am using the write to measurement file express VI in my code and I have wired into it a control that sets the location to save the measurement file
    The only problem is the measurement file has to exist first!! I cant for example, from the front panel, click the browse directory box, navigate to a folder and type in a name for the file. It just says file not found! Its like the file directory control is opening a file to save to, rather than creating a new file in that location
    How can I solve this?
    Solved!
    Go to Solution.

    Project attached
    If I go in browse options what do i do? Just chose new and existing files?
    Attachments:
    engine.zip ‏119 KB

  • Reader is stuck on one file and wont load a new file why?

    reader is stuck on one file wont load a new file why?

    Hey george,
    Could you please let me know if you are using the latest version of Adobe Reader i.e. 11.0.10
    What OS version are you using?
    Have you opened the file on the web or within Reader itself?
    You might close the file, launch Reader and go to Edit> Preferences> Security(Enhanced) and uncheck 'Enable Protected Mode at startup' option.
    Let me know if this sorts your problem.
    Regards,
    Anubha

  • Writing to specific cells of existing Excel file and saving as a new file using LV 8.6

    Hi all,
    I am new to LV and am currently tasked to create a program that can open an existing excel file, input data in the program that will be written to a specific cell in the excel file and then saving the current edited file as a new file.
    I have browsed through all the forums but I am unable to view the examples sent in them as I am using LV 8.6 which is why I am still having trouble visualizing how to create a program like this. Can anyone help me and mentor me how to write this program in this version of LV? I do not have a microsoft office toolkit hence another approach could be preferred. Thank you.
    Aaron
    Solved!
    Go to Solution.

    Thank you for helping me on this. However I do not really understand how does ActiveEx work. I have created a Vi according to the picture that you provided but there was some error in running the file.
    Below is my own VI that I am trying to create. It consists of multiple string inputs which I am trying to input each into an existing file. I have created a separate txt file which has the cell numbers. I am trying to allocate each string into each respective cell in an existing file. I am currently having the problem of doing this "allocation" of each string as I do not have the microsoft office tool kit. Is there any other way for me to do so?
    Also, I would like to save the newly created file as a new file with the name as seen in my VI. How would I be able to do it?
    Please help me as I am stuck here but do not know how to continue
    Attachments:
    untitled.JPG ‏33 KB

  • File Sharing Permissions Problem When NEW Files Created

    My wife & I have a home office network setup for our business, and are having trouble with shared files over the network. We're both on Macs, and all of our client files reside on an internal hard drive in my Mac Pro. I've set her up as a "Sharing Only" user on my computer (which matches the username & password of her account on her iMac), and have properly setup file sharing in both the System Preferences, and in the directory itself that we want shared. I've also applied the permissions to all files & folders below the main folder, and she can view, open and save whatever she needs and it works great.
    *Here's where the problem comes in...* If either of us create a NEW file or folder, the other person doesn't have WRITE access to it (we can browse and open it fine). The second I go to update a file she created, it won't let me over-write it, and I have to go into the permissions for that specific file and give myself Read/Write access. I've experimented with "Groups", and assigned both of us a special group, and applied that group access to that directory, but it doesn't make any difference when a NEW file or folder is created - it doesn't copy the parent directory permissions to itself, it makes one of us the owner, and nobody else has access.
    Is there any way around this? We're both constantly creating new files, and it really hampers our workflow to have to keep re-applying file permissions every time one of us creates something new. Ideally, any new files created within that main client folder would automatically have the same permissions as the parent directory. Any help would be greatly appreciated! Thanks!!

    Here's how to do this with Access Control Lists.
    1) Go to System Preferences -> Accounts. Unlock the padlock. Click the + button. Make a new group. Call this group "sharing" for the purposes of this exercise. Add the users you want to the group.
    2) Make a new empty folder in /Users/Shared. Call it "sharefolder".
    3) Log in to an admin account and paste all three of these lines at once into Terminal:
    sudo chmod +a "sharing allow delete,chown,list,search,add_file,\
    addsubdirectory,delete_child,file_inherit,directoryinherit" \
    /Users/Shared/sharefolder
    4) From now on, any files you create or copy to the sharefolder or to any of its subfolders will inherit read+write permission for all users in the group. If you have any existing files that you want to move into the sharefolder, a simple move by drag & drop won't cause the permissions to propagate. you need to hold down the option key while dragging them in. This will copy them over, ensuring that the ACL permission is properly inherited.
    One other caveat: Files created by a small number of OS X apps won't inherit the permissions properly if saved directly into the ACL folder hierarchy. TextEdit is one such app. Save TextEdit files in a temporary location first, and then copy them in. Then they will have the correct permissions.

  • File adapter. Only get new files

    Hi there,
    I have a small problem that I'm not able to solve that easily with XI.
    I have some directories that I need to get files from on a remote server. The only problem is i need to get only the new files and I am not allowed to delete the old files. Since we are not the only one getting those files.
    So far I have not found any option to keep the old files and only get the new ones. Does anybody know a neat trick to get only the new ones?
    Regards,
    Wietse

    > Hi again Wietse,
    > After configuring the file adapter the way i
    > mentioned,check for performance, you might need to
    > install remote Adapter engine if you have some FW
    > problems or other security barriers that turn the
    > processing of this file to a hassel over the net.
    >
    > Nimrod
    Problem still is I am not allowed to do anything else then ftp/get on the files. I can't install a remote adapter engine or change anything to the files.
    I hoped that it would be possible to store the filenames somewhere and compare a dir listing to the stored filenames before the real get is done. But even when writing an adapter module, the file will already be in the adapter once the module kicks in. And I don't want to get old files that I've already processed into my system since there is a huge history of files on the machine.
    I think I might end up writing a perl script that searches for the new files and gets them and them sends them through to XI using a SOAP call.

  • Reducing the time interval in file Adpt to write a flat file at a location

    Hi All,
    I hav a scenario where i hav to write a flat file (<b>XXX.txt</b>) to a location. b4 doing that, i hav to check whether <b>XXX.txt</b> already exists or not. If it doesn't exists then i hav to write the <b>XXX.txt</b> file there. if it already exists, then i hav to wait until that <b>xxx.txt</b> file gets deleted.
    In the receiver file adapter v hav an option <b>file construction mode = <u><i>create</i></u></b> which does the same thing. but the problem here is it is taking too long (<b>more than 5 min</b>) which is not at all acceptable in my case (it is ok <b>if it takes 1 min</b>).
    Is there any way to <b>reduce the time interval</b> using the same option?
    Or do we hav any <b>work around solution</b> for acheiving the same scenario?
    any help wud b appreciated.
    Thnx in Adv.
    Anil

    Anil
    As far as my knowledge goes I think it is not possible because we are not going to do anything from our end. XI is doing processing and creating a file for you. But you might be sending a large file at a time. So you have to improve the performance in your scenario. You check this urls on how to improve performance in XI:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/70ada5ef-0201-0010-1f8b-c935e444b0ad
    Improving performence in XI
    Maximum Permitted File Size in XI
    ---Satish

  • CCMS File Monitoring - Autoreaction for every new File

    Hi Experts,
    I have a folder with xml files. I monitor these files with the sapccmsr agent. this works fine. Now I want to establish an alerting for the files. If in one of these files contains the pattern "error", I want to generate an alert. I have generated a logfile template like here:
    LOGFILE_TEMPLATE
    DIRECTORY="E:/usr/sap/prfclog/sapccmsr/Test/"
    FILENAME="*.xml"
    MONITOR_FILESIZE_KB=1
    PATTERN_0="Error"
    VALUE_0=RED
    if in a file the pattern "Error" exists the colour in rz20 is changed to red. this is working ...
    now I come to my problem:
    the names of the monitored files are changing. for example there is a file with the name "file_0.xml". the next day a new file with the name "file_x.xml" exists. so, for the alerting with autoreaction it is necessary that the system gives the autoreaction to each file in the monitor automaticly. is it possible? how can i solve this problem?
    best regards
    christopher

    Hello Christopher,
    > the names of the monitored files are changing. for example there is a file with the name "file_0.xml". the next day a new file with the name "file_x.xml" exists.
    you monitor all theses files. The wildcard in the parameter "FILENAME" ensures this:
    > FILENAME="*.xml"
    > so, for the alerting with autoreaction it is necessary that the system gives the autoreaction to each file in the monitor automaticly. is it possible? how can i solve this problem?
    A short look into the [online documentation|http://help.sap.com/saphelp_nw70/helpdata/EN/cb/0f8897c23b414ab6e562aa913971bc/frameset.htm] returns the parameters AUTOREACTION_LOC and AUTOREACTION_CEN.
    Maybe they will be helpful?
    Regards, Michael

  • Extra empty groupName in TDMS file when using DAQmx Start New File & stop DAQmx while waiting for trigger?

    I wrote a VI that listens to an external trigger coming from a PFI line and saves a user-defined number of pretrigger+posttrigger samples into disk, and then the DAQmx restarts to wait for the next trigger. I used the DAQmx Start New File.vi to change the filename of each of the next file. However, I found that for each of the resulting TDMS files, there is an additional group that is added in addition to the real data. For example, if the groupName is set to "task_voltage", then there is an additional groupName called "task_voltage #1".
    I suspect that this is because the program preallocate diskspace using the old filename for the pretriggered samples, but when the trigger happens and the samples are ready to be written into disk, an actual new file is opened and saved. The reason I think this might be the case is because, say each file would be 50kB and I already have 1 file triggered and saved, before the second trigger comes in, I can see that the file size of the first file is twice as much as it should be (100kB), but the file size will return to noraml (50kB) after the second trigger happens and a second file is created.
    Does anyone know if this is really the case? Is there a way to configure the task so that this doesn't happen?
    Another question I have is that the program currently set up so that the VI will wait until a trigger happens to return the values. However, this means that if a trigger doesn't happen, the VI waits indefintely, and the "stop" button in the while loop is useless. I have to use the "Abort Execustion" button on the tool bar to stop the VI. Is there a way to interrupt and stop the DAQmx task even if the trigger doesn't happen?
    Thanks in advance for any help!
    Attachments:
    pretrigger_loop_new_file.vi ‏29 KB

    I don't believe there is a way to programmatically change/delete the group name in a TDMS file. What you can do however, is convert between TDMS and TDM using the VIs found in the Data Storage palette and then perform whatever modifications you need using the TDM utilities.
    Applications/Systems/Test
    National Instruments | AWR Group

  • How to save new edits and text to photo without creating a new file

    I am a new user of PSE 7.  I am able to enhance and add text to my photos but can't save the edits without creating a new PSD PSE file in addition to the original unedited photo.  How do I save the phto itself as edited?

    99jon wrote:
    If you really want to make your changes irreversible then use “Save As” and select file type from the dropdown list e.g. jpeg and enter the exact same file name as the original. Click OK to save and OK to overwrite the original.
    While this of course is the answer to the question, the idea of overwriting the original is simply a bad idea. If you do this, you can never get back to your original and start again. That text will always be there.
    I advise the original poster not to do this. Save your edits as a different name.

  • Read text from a string control in a compiled LabView executable from C#

    I have a third party complied LabVIEW executable and no source code.  I need to read values from the front panel in C#.  I know that LabVIEW controls and indicators are not actual windows.  Is there a way to programmatically access this information(i.e. without using screenshots and OCR)?  I couldn't find this exact question answered in this forum.  I've read a few things about VI Server doing this from LabVIEW, but I don't think you can access VI Server from C#.  Any help would be appreciated.
    Thanks in advance.

    You should certainly be able to access VI Server from C#. LabVIEW has an ActiveX server built in that allows other applications to access a sizeable subset of VI Server functionality. I would guess you could access ActiveX servers directly from C#, but the worst-case scenario would be to wrap the ActiveX calls into a .NET assembly. I've seen this done before. This blog entry is slightly off topic, but might help you.
    Actually, I do need to revise this answer... If you are working with a LabVIEW DLL, the DLL would have to be compiled with the ActiveX Server option enabled. Otherwise, LabVIEW won't include the code that allows the DLL to be hooked into using this method. So if you don't have the source and you can't recompile it, you might be out of luck. Does the DLL really not have a function that exports this string value?
    Message Edited by Jarrod S. on 10-26-2006 01:39 PM
    Jarrod S.
    National Instruments

  • How can I search a file system and only return newer files?

    Sorry the title didn't give me much room to work with. I'm writing a tool which needs to track all the files in an OS. What I'd like to do is make it so my program will only return files that have been modified/created since the last search to add to my program. I was wondering if there's an efficient way to do this other than checking each file's timestamps? Also is there a way to tell from a parent directory whether any files in its directory have been modified/created? I'm looking for ways for Windows and Linux.

    I have no problem checking timestamps but it can be rather time consuming doing this. I don't know if this is quicker but I'd like to sort by modified date and check the time stamps for newer timestamps than the last time I ran. This way if I hit a time stamp equal to my last run I know to stop there. I checked Windows and the folder does tell you whether any file was created/modified in it's directory. However, if a file is created in one of its children's directories it won't update the time stamp. It's unfortunate because I could've avoided the search at a higher level directory otherwise. Without this I'll have to walk the whole structure one way or another. I can still improve the speed but I can't make it as efficient as I'd like.

  • Can't open myFlash CS6 file or even open a new file

    Hello, my name is Serena Oden and I install Flash CS6 onto my windows 8.1 Toshiba laptop that’s run 64 bits and 500 GB / 4.00 GB(3.57 GB usable). Photoshop CS5 (64 bit) , After Effect CS6 , and Illustrator CS6(64) works fine on my laptop and Flash CS6 runs just fine recently in early to mid-month of February of 2015. When I open a new flash file or recent flash file, and took forever to load up file and  said “not responding” . The percentage of the CPU or Memory of my laptop in the task manager became high that I have to end task of my flash, can you please help solve this problem. Thank you , Serena oden

    Hi David,
    Can you please attach your log file to help us figure out what's going wrong? Here's how you can find it:
    1. Open up the Terminal (in Applications/Utilities).
    2. Type the following and then press enter:
    cp Library/Application\ Support/Adobe/Flash\ Catalyst/workspace/.metadata/.log Desktop/log
    3. You should see a file called log on your Desktop. Attach this file to your post.
    Thanks!

Maybe you are looking for

  • Time Capsule 80211N / Airport Extreme 80211B/G/N

    Hi! I have a new Time Capsule currently set up using 80211B/G/N. This is because I have an Airport Express connected to an Apple Hi-Fi. Also an iPhone that is not compatible with N. Would it be possible somehow to connect my old Airport Extreme as a

  • AV cable from ipod touch to TV

    I have a 1st generation ipod touch with the version 2.2 software. When I use my AV cable connection to my TV and play a video or view photo's the images are always black & white, but the audio is fine. This is my second cable & the same thing happens

  • Error when building exe

    Building an application with database connectivity toolset v 1.0.1. aplication builder crashes and gives error resource.cpp

  • I had succeeded in navigation while i used [b]valueChangeListener[/b]

    After learning in the forum, i had succeeded in navigation while i used the attribute valueChangeListener in the tag h:selectOneMenu. Cheers. Here is my some codes about this: in # faces-navigation.xml # <navigation-rule>           <from-view-id>/jsp

  • IPod USB 2.0 ports 32-bit Windows 7

    I have a new 16GB iPod Nano 7th generation. My computer says has malfunctioned when I plug it into any USB port (I have 5).  I have installed the latest iTunes software and my Windows 7 is updated.  My computer is 5 years old, is 32-bit and has has 2