Reading and Writing from a text file at the same time

I know who to use the Scanner and PrintWriter to read from and write to a .txt file. But these are limited. How can I read and write at the same time? Such as open a file and change every third character or change every second word to something else and then write it back. I found this [http://java.sun.com/docs/books/tutorial/essential/io/|http://java.sun.com/docs/books/tutorial/essential/io/] but its a little over my head. Is this the only way to do it?

wrote:
You are using buffered reads and writes I would assume, right? Also, how do you think most programs handle this sort of thing? I don't believe I'm using buffering.
My code looks something like this
//...necessary imports
//then
Scanner inFile = new Scanner (new file("filename1.txt"));
PrintWriter outFile = new PrintWriter ("filename2.txt");
//then stuff like
int x = inFile.hasNextInt();
outFile.println(x);
camickr wrote:If you are changing the data "in place", that is none of the data in the file is shifted, then you can use a RandomAccessFile.
Otherwise, you've been given the answer above.What is RandomAccessFile? Is it what I have a link to? Basically what I do is I write a bunch of numbers to a txt file and then change the numbers I don't need anymore to 0. So say I had 0 1 2 3 4 5 6 7 etc. I would like to to open the txt file and change every second one to 0 so then I'd have only odd numbers and 0s.
I looked at the documentation for RandomAccessFile and it seems like it might be what I need.
Thankyou both for your help so far. I took a java course in high school and they only taught me one way to get data from text files and that is what I just showed you. So maybe this questions are really stupid. lol
Edited by: qw3n on Jun 13, 2009 7:46 PM

Similar Messages

  • How can I plott data from a text file in the same way as a media player using the pointer slide to go back and fort in my file?

    I would like to plott data from a text file in the same way as a media player does from a video file. I’m not sure how to create the pointer slide function. The vi could look something like the attached jpg.
    Please, can some one help me?
    Martin
    Attachments:
    Plotting from a text file like a media player example.jpg ‏61 KB

    HI Martin,
    i am not realy sure what you want!?!?
    i think you want to display only a part of the values you read from XYZ
    so what you can do:
    write all the values in an array.
    the size of the array is the max. value of the slide bar
    now you can select a part of the array (e.g. values from 100 to 200) and display this with a graph
    the other option is to use the history function of the graphes
    regards
    timo

  • Reading and writing to a text file from an Applet

    I'm a novice java programming with very little formal programming training. I've pieced together enough knowledge to do what I've wanted to do so far...
    However, I've been unable to figure out how to read and write to a text file from an Applet (I can do it from a normal java program just fine). Here is a simple example of what I'd like to do (you can also look at it on my website: www.stat.colostate.edu/~leach/test02/test02.html). I know that there is some problem with permission/security but I'm not smart enough to understand what the error messages are telling or understand the few books I have. If anyone can tell me how to get this applet to work, or direct me to some referrences that would help me out I'd really appreciate it.
    Thanks,
    Andy
    import java.applet.Applet;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    public class test02 extends Applet {
    public Button B_go;
    public GridBagConstraints c;
    public void init() {
    this.setLayout(new GridBagLayout());
    c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    B_go = new Button("GO");
    c.gridx=1; c.gridy=0; c.gridwidth=1; c.gridheight=1;
    c.weightx = c.weighty = 0.0;
    B_go.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    print_stuff();
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    this.add(B_go,c);
    public static void print_stuff() {
    try{
    File f = new File("test02.txt");
    PrintWriter out = new PrintWriter(new FileWriter(f));
    out.print("This is test02.txt");
    out.close();
    }catch(IOException e){**/}
    }

    I have almost the exact same problem, and I am in the same situation as you are with respects to the language.
    I am simply trying to create a file and output some garbage to it but my applet always spits back a security violation. I've tried eliminating the restrictions on the applet runner I use but I still get the error.
    My method:
    debug = new Label() ;
    debug.setLocation( 20, 20 ) ;
    debug.setSize( 500, 15 ) ;
    add( debug ) ;
    // output
    try
         OutputStream file = new FileOutputStream( new File( "" + getCodeBase() + "output.txt" ) ) ;
         byte[] buffer = { 1, 2, 3, 4, 5 } ;
         file.write( buffer ) ;
         file.close() ;
    } catch( Exception e )
         debug.setText( e.toString() ) ;
         Can anyone tell why this isnt working?

  • HP DV7 laptop, cant listen and talk from 2 usb headsets at the same time??

    Hi,
    I am trying to use two usb headsets at the same time as my wife and I are doing an online course, but can onle use either one at onc, not both?? Has anyone got any ideas?
    Thanks, Matt

    Hello Mattynsavvy, welcome to the HP Forums.
    It appears that you're trying to use two headphones from your notebook to do an online course.
    The way that you're trying to do this probably won't work. The notebook itself only has one sound card. This card can only output audio to one device at a time. So if you have both USB headsets into ports. Only one will have sound. Just like how the headset cuts off the speakers. You would need a second sound card, or to be using speakers or another computer.
    The only thing I could think of that may accomplish what you're trying is to use the audio/mic jacks on the notebook specifically with a splitter. This may allow the sound to be direct to two headsets. I can not say for certain if this will work or not.
    I was able to find a few YouTube videos with various ways to achieve what you're trying to do, but as they run with 3rd party software attempting those suggestions would be completely up to you.
    I hope this helps.
    Thank you for posting on the HP Forums.
    I worked on behalf of HP.

  • InCopy CS4 and InDesign CS4 cannot open file at the same time!

    I have 2 editors that make changes in my indd file. The one editor is able to open the file concurrently with myself (i'm in indesign) just fine. But when the other editor wants to open the file....I cannot open the indd file and vice versa. We are PC based.
    shane

    Yes, we are all working on the same server.
    And Yes on the Editor A / scenario 1  (Designer opens file and Editor A opens file concurrently). works fine.
    Editor A closes out of Incopy and so does Designer. Editor B opens the file and Designer tries to open the indd file and now the designer gets the warning: Cannot open document. You may not have permission or the document may be open already. This is the same error if the Designer opens the file first and Editor B tries to open it while the designer has it open.
    Editor A and B are able to have the file open at the same time no problem.
    Also this happens to all indd files that Editor B tries to open. So it is not linked to a problem with the file.
    one other note: on the server just above the indd file...when Editor B has the indd open in InCopy... a 'temporary' Indesign Lock File appears.
    shane

  • Reading and Writing to a Text File

    Hello all,
    I was wondering if it is possible to write from forms to a text file and if possible what is the best way to do it.
    Thanks,
    Bucky

    Use the TEXT_IO built-in functionality in forms or from the database utl_file. TEXT_IO seems to be more flexible because you can read and write to any server/directory you have access to whereas UTL_FILE is limited to the server where the database is located. Hope this helps.
    Mike

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

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

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

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • How do i read complete line from a text file in j2me?????

    how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..

    That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..

  • I need to know how to edit a drawing - basically remove the arrows and text but at the same time match the background of the existing pic. then re add new text. how do i erase the arrows and text and arrows but match current background of pic. step by ste

    i need to know how to edit a drawing - basically remove the arrows and text but at the same time match the background of the existing pic. then re add new text. how do i erase the arrows and text and arrows but match current background of pic. step by step explanation please beginner

    Please post (a relevant section of) it right on this Forum.

  • Is there a way to keep selected apps that you have on your admin account inaccessible and unseen from another admin account on the same Mac?

    My sister and I share computers, but it's really her Mac because she got it for her birthday.  I'm using it because there is no other place to hold my iTunes library, documents, photos, etc.
    She complains that I make the computer too slow after I downloaded/installed too many apps from the Mac App Store using my admin account and my iTunes account.   However, they show up on her account as well, and she doesn't want to see them or have her computer slow down, so she deletes them.  Is there a way to make certain apps unseen and inaccessible from other admin users on the same machine?

    Only by storing them on an encrypted disk image. Anyone who has an administrator password to a Mac can use it to access all unencrypted data on the system.
    (59941)

  • Save as PDF and AI file at the same time?

    Hey everyone,
    I was wondering if it's possible to save an AI file as both an AI file & PDF file at the same time??
    Where i work, we always need to save an AI file and a PDF file. So is there a way I can set up my Illustrator so everytime i save something, it'll  save the AI file and automatically create the PDF too? ..
    Or is there no way around .... Save as: Illustrator file.  /   Save as: PDF file in two separate actions?...
    Any help would be greatly appreciated.
    Thanks!
    Jay

    I was wondering if it's possible to save an AI file as both an AI file & PDF file at the same time??
    Where i work, we always need to save an AI file and a PDF file. So is there a way I can set up my Illustrator so everytime i save something, it'll  save the AI file and automatically create the PDF too? .
    No, it is not possible in the base product.
    (I guess it is probably doable with scripting, I'll defer to others on that.)
    But can you stop and tell us why you want to do this?
    AI files with "Preserve PDF Compatibility" and PDF files with "Preserve Illustrator Editing Capabilities" are functionally equivalent. Both of which are the default. In both cases, the file contains a PDF portion that is visible to PDF viewers, and an Illustrator private data section that is used by Illustrator. Two entirely complete versions of the information that can stand on their own appear in both file types.
    While I realize the requirement may be beyond your control, it would still be good to understand it's origin.

Maybe you are looking for

  • Separate "iMessage accounts" on two iPhones with the same Apple ID

    I have two iPhone 4 handsets. One is for work and one is my private number. Currently I am using the same Apple ID on both phones, as I want to use the apps I've purchased on both devices and get my contacts from iCloud. As I usually bring both hands

  • Sending text file out of sap

    Hi All I have this requirement I have to read vendor data in sap , create a text file of this data in the daily basis and send the text file to a third party system. I know how to read data and create the file , but how can I send this file to other

  • Calling transaction from Workitem - Credit Management workflow

    Hi, Our client have a requirement to have a link in the workitem and when we click on the link it should open transaction S_ALR_87012218. The requirement in Credit management workflow, in which we are having included object as sales order, when we cl

  • Since last sync on iPod Touch 1g, music crashes after playing 1st song.

    Since the last sync on my iPod Touch 1g, both the 3rd party apps and the music app would crash after opening (music after playing 1st song).  I found a fix online for the apps, but how do I get my music to play again?

  • Manage Distribution Edit Installer problem

    I am using Labwindows 8.1 I have a small project that I am having problems building. When I go into the Manage Distributions, click edit and then go to Drivers & Components, there are several components checked that are not needed . I am not sure how