开发者

How To Read \n(enter) and \b(space) from a file and store it in an array of characters using java

I want to read data from a file including the space and enter and store it in开发者_C百科 an array of characters. please help me to solve this problem


You can try FileUtils.readFileToString(filename) e.g.

String allTextInFile = FileUtils.readFileToString("my-file.txt");


Use FileReader http://download.oracle.com/javase/1.5.0/docs/api/java/io/FileReader.html. Its contract is:

Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.

This will preserve the \n and other characters.

Also consider using the Apache library http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

where the method http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File%29

public static String readFileToString(File file)
                               throws IOException

Reads the contents of a file into a String using the default encoding for the VM. The file is always closed.

To get the character array, use the String method http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#toCharArray%28%29

public char[] toCharArray()
Converts this string to a new character array.

Returns:
    a newly allocated character array whose length is the length of

this string and whose contents are initialized to contain the character sequence represented by this string.

If this is not what you want you will need to explain further

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜