Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    Regular Coder
    Join Date
    Dec 2004
    Posts
    202
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Java Help-File Reading & Writing

    I am having problem and just need some coding lines that reads a file into an array so it can be edited in the array and than rewrites it to the file later on. Also another question, is there a way to add more to an array with out creating a new one and so forth?

  • #2
    cfc
    cfc is offline
    Regular Coder
    Join Date
    Dec 2004
    Location
    Keswick, Ontario
    Posts
    251
    Thanks
    0
    Thanked 0 Times in 0 Posts
    1. BufferedReader has a readLine method. nio probably doesn't have anything as high-level as that, but it should be capable of offering similar functionality with some additional code (detecting '\n' in a CharBuffer I think). When you can read the file one line at a time, you can index each line in an array or Collection. PrintWriter offers a writeln() method for putting it all back in.
    2. Not an array, take a look at the Collection framework.
    Last edited by cfc; 03-17-2005 at 02:46 AM.

  • #3
    Regular Coder
    Join Date
    Dec 2004
    Posts
    202
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ok ok a bit confused about that whole collection thing and the file read and write. I first need to get it to read the file and add each line into an array and than it runs the rest. When you add some more stuff to the array it adds to entrys to the array so that the length goes from like 6 to 9 and the new ones get filled. Than i want to get it to erase the document and create it again and write the whole array to it so that each part of the array is on a new line. If possible get it to replace the documents content so that it like scans it to see if any changes accured and than only add those changes in the right lines. I think now i am may be confusing some people but if you have a sample program you know of that reads a files than buts it into an array and you can add more strings to the array untill you close the program and so forth if you understand that thank you for understanding it.

  • #4
    cfc
    cfc is offline
    Regular Coder
    Join Date
    Dec 2004
    Location
    Keswick, Ontario
    Posts
    251
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Lists, Maps, etc. are all Collections that can be iterated over and can be expanded to fit your data.

    Read this for more details:
    Chapter 11 of Thinking in Java, 3rd Edition

    It's long so I recommend saving it rather than viewing it on my server which will only be online for about 3 more hours today.

  • #5
    Regular Coder
    Join Date
    Dec 2004
    Posts
    202
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ok bit confused still but not as much tell me how i would create a container add a string and get just that one string. Should just be 3 lines ok?

  • #6
    Regular Coder
    Join Date
    Dec 2004
    Posts
    202
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ok i looked it over and here is what i understand so far and i put together a example

    List test = new ArrayList();
    test.add("bob");
    System.out.println("" + test.get(0));

    but there errors are line one with the word List and ArrayList() help?

  • #7
    cfc
    cfc is offline
    Regular Coder
    Join Date
    Dec 2004
    Location
    Keswick, Ontario
    Posts
    251
    Thanks
    0
    Thanked 0 Times in 0 Posts
    For the sake of coming closer to what you'll probably want to use:
    Code:
    import java.util.*;
    
    public class ArrayTest {
    	public static void main (String[] argv) 
    	{
    		List test = new ArrayList();
    		test.add("foo");
    		test.add("bar");
    		Iterator it = test.iterator();
    		while (it.hasNext()) {
    			System.out.println(it.next());
    		}
    	}
    }
    The code you posted compiled and ran fine for me, placed in the above ArrayTest class. The compiler noted the declaration of an ArrayList as type List but it didn't stop it from compiling.
    Last edited by cfc; 03-18-2005 at 03:33 AM.

  • #8
    Regular Coder
    Join Date
    Dec 2004
    Posts
    202
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I figured it out!
    Needed import java.util.*; and i didn't know about it so thanks

  • #9
    New Coder
    Join Date
    Mar 2005
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Although using java.util.* is perfectly acceptable, it is better to only import exactly what you need, in this case: import java.util.ArrayList. This way you only pull in what you need and not the everything in Collections.

    In Java 1.5+, you can also specify the type of data you will be storing in there (autoboxing) like so: ArrrayList foo = new ArrayList<String>(1024); This makes it so that you can only place Strings into the ArrayList, but you also don't have to cast the object to a String when you pull it out. You'll find that by doing that, you will save yourself some typing down the road.

  • #10
    New Coder
    Join Date
    Mar 2005
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by cfc
    [list=1][*]nio probably doesn't have anything as high-level as that, but it should be capable of offering similar functionality with some additional code (detecting '\n' in a CharBuffer I think).
    NIO doesn't even make it that easy.

    Ok, here's the standard IO version
    Code:
    import java.io.File;
    import java.io.FileReader;
    import java.io.BufferedReader;
    
    public class SampleFileReader
    {
    	public static void main( String args[] )
            {
    		try
    		{	
                		File fp = new File( "SomeFileSomewhere.txt" );
                		FileReader reader = new FileReader( fp );
                		BufferedReader input = new BufferedReader( reader );
                		String line;
    
                		while( (line = input.readLine()) != null )
                		{
                     		System.out.println( line );
                		}
    
    			reader.close();
    		}
    		catch(Exception e) { e.printStackTrace();	}
            }
    }
    And here's the NIO version. We're just reading in and printing out. If you want "readline" capability, you have to build that in which requires a bit more coding and is slightly more complex. I HIGHLY recommend the standard version for the original poster.
    Code:
    import java.nio.ByteBuffer;
    import java.nio.channels.ReadableByteChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.io.FileInputStream;
    
    public class SampleNIOReader
    {
    	public static void main( String args[] )
    	{
    		try
    		{
    			Charset charset = Charset.forName("ISO-8859-1");
    			CharsetDecoder decoder = charset.newDecoder();
    			ReadableByteChannel chan = new FileInputStream("someFileSomewhere.txt").getChannel();
    			ByteBuffer bBuf = ByteBuffer.allocate(1024);
    			int bytesRead = 0;
    			while( bytesRead >= 0 )
    			{
    				bBuf.rewind();
    				bytesRead = chan.read( bBuf );
    				bBuf.flip();
    				System.out.println( decoder.decode(bBuf).toString() );
    			}
    			chan.close();
    		}
    		catch( Exception e ) { e.printStackTrace();	}
    	}
    }
    ** Please note that the above code snips are NOT production quality, but should give you and a good idea as to how to read a file in. In your code, you should do some error handling, etc.
    Last edited by hinokata; 03-23-2005 at 07:10 AM. Reason: Absent mindedness

  • #11
    New to the CF scene
    Join Date
    Jun 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Read and write from and to a file in Java

    /* For those who need this code to read from a file and write to a file */
    /* This is a better and simpler approach to read and write file in java*/

    import java.io.*;

    class Filetransfer
    {public static void main (String args[])
    {try
    {

    FileReader fr = new FileReader("inputfile.txt"); // use any filename
    BufferedReader br = new BufferedReader(fr);
    int inputline;
    FileWriter fw = new FileWriter("outputfile.txt"); //use any filename

    while((inputline =br.read()) !=-1) // check to see if the file has ended
    {
    fw.flush();
    fw.write(inputline);

    }
    fr.close();
    fw.close();
    }catch (IOException e){}; /* Program by Sumish Darak*/ } }

  • #12
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I am trying to open a file where a file name is having spaces.

    i am trying to do it by file= new File(path) but it is giving me an exception .



    illegalArgumentException
    at java.net.URI.create(URI.JAVA:842)


    could you suggest me any solutions


  •  

    Posting Permissions

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