Putting the content of a .txt into a String
I don't like to ask questions that have been answered a lot, but I kinda need to right now.
I'd like to have a method for a project to extract the content of a .txt file into a String variable (then manipulate the String). What I need is a clean and compact way to do that. I already know that the only 3 characters the String will be able to contain are "." "*" "\n" (or "\r\n" if the file had been created in Windows).
Basically I already created a class called TextFile which has a String variable and there is a method called importFile that takes a String as an argument (and that string is the path of the .txt file).
I know I will have to deal wi开发者_开发技巧th exceptions and all but I'm not really at ease with that either.
Could you please help me?
Here's what I use. You may want to modify it or totally, throw it away. Either way, you won't hurt my feelings.
public static String readFileAsString(String filePath)
throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
fileData.append(buf, 0, numRead);
}
reader.close();
return fileData.toString();
}
Can you simply use commons-io to do that? see http://commons.apache.org/io/api-release/index.html?org/apache/commons/io/input/package-summary.html
精彩评论