Java File Reading (read the function of each line and all content)

Source: Internet
Author: User
Tags readfile

/*
A class containing methods useful for manipulating
Text Files
1. readfilebyline:
Reads the contents of a text file line by line
And returns a string array representation, where
Each line is stored in an element of the array.
2. readfile
Read the contents of a text file into a string
*/

Import java. Io .*;
Import java. util .*;

Public class textmaniptools {

/*------------------------------------------------*/
@ Suppresswarnings ("unchecked ")
Public static string [] readfilebyline (string filename ){
Arraylist filecontents = new arraylist ();
String [] F;
String inputline = new string ();

Try {
Bufferedreader bin = new bufferedreader (
New inputstreamreader (
New fileinputstream (
New file (filename ))));
Int line = 0;

While (inputline = bin. Readline ())! = NULL ){
Filecontents. Add (inputline );
Line ++;
}
}
Catch (exception e ){
System. Out. println ("an error occurred during file reading" + E );
}

F = new string [filecontents. Size ()];
For (INT I = 0; I <filecontents. Size (); I ++ ){
F [I] = (string) filecontents. Get (I );
}
Return (f );
}

/*------------------------------------------------*/
Public static string readfile (string filename ){
Inputstream in = NULL;
Byte inputbuffer [] = NULL ;;

Try {
In = new fileinputstream (new file (filename ));
Inputbuffer = new byte [IN. Available ()];
In. Read (inputbuffer );
}
Catch (exception e ){
System. Out. println ("an error occurred during file reading" + E );
}
Return (new string (inputbuffer ));

}

/* ---- Just to test --------------------------------*/
Public static void main (string [] ARGs ){
String filename = ARGs [0];
// String [] filecontents = textmaniptools. readfilebyline (filename );
String filecontents = textmaniptools. readfile (filename );
System. Out. println (filecontents );
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.