Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   Java I/o Help (http://www.programmingforums.org/showthread.php?t=1016)

FidI Nov 2nd, 2004 10:04 AM

i ve been trying to find a way to successfully read text files and the be able either to read their data on screen or write their data to another text file.unfortunately i have not achieved yet.could anybody please write me a simple example of java code which reads for example the first,third and fourth line of a text file and another program that reads and writes the same lines to another text file?how can i read the entire file contents?
i am sorry i am asking so many things but i am disappointed and confused.... :(

thanks in advance guys :)

sykkn Nov 2nd, 2004 10:21 AM

Reading a file's contents: (from http://javaalmanac.com/egs/java.io/R...sFromFile.html)
:

* *try {
 * * * *BufferedReader in = new BufferedReader(new FileReader("infilename"));
 * * * *String str;
 * * * *while ((str = in.readLine()) != null) {
 * * * * * *process(str);
 * * * *}
 * * * *in.close();
 * *} catch (IOException e) {
 * *}


Read from one file and write to another: (from http://javaalmanac.com/egs/java.io/CopyFile.html?l=new)
:

* *// Copies src file to dst file.
 * *// If the dst file does not exist, it is created
 * *void copy(File src, File dst) throws IOException {
 * * * *InputStream in = new FileInputStream(src);
 * * * *OutputStream out = new FileOutputStream(dst);
 * *
 * * * *// Transfer bytes from in to out
 * * * *byte[] buf = new byte[1024];
 * * * *int len;
 * * * *while ((len = in.read(buf)) > 0) {
 * * * * * *out.write(buf, 0, len);
 * * * *}
 * * * *in.close();
 * * * *out.close();
 * *}


hope that will help get your started. Note the classes used to read and write. You can find them in the JavaTM 2 Platform, Standard Edition, v 1.4.2 API Specification under java.io

FidI Nov 2nd, 2004 10:29 AM

thank you very much mate!i ll check them out!:)

Mjordan2nd Nov 4th, 2004 6:04 PM

Also, check out the new Scanner class. Much easier for input, in my opinion.


All times are GMT -5. The time now is 8:03 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC