private String readFile(String filePath, BufferedReader reader)
throws FileNotFoundException, IOException {
codeString = null;
int i = 0;
FileInputStream fis = new FileInputStream(filePath);
if (reader == null)
reader = new BufferedReader(new InputStreamReader(fis));
String line = reader.readLine();
while (line != null){
line = line + reader.readLine();}
return line;
}
throws FileNotFoundException, IOException {
codeString = null;
int i = 0;
FileInputStream fis = new FileInputStream(filePath);
if (reader == null)
reader = new BufferedReader(new InputStreamReader(fis));
String line = reader.readLine();
while (line != null){
line = line + reader.readLine();}
return line;
}
static public String readtoEnd(Reader reader) throws IOException {
final int totalLength = 1024;
char[] recvChars = new char[totalLength];
int readLength = reader.read(recvChars);
String strResult = "";
while (readLength>0){
strResult = strResult.concat(new String(recvChars).substring(0,readLength));
if(readLength < totalLength)try{Thread.sleep(20);}catch(InterruptedException e){}
readLength = reader.read(recvChars);
}
return strResult;
}
这是个比较通用的读流的全部数据的方法,可以读文件流、网络流等。
public String getText(String filePath) {
File textFile = new File(parentPath+filePath);
byte[] bf = new byte[1024];
int read;
StringBuffer textContent = new StringBuffer();
FileInputStream from = null;
try {
from = new FileInputStream(textFile);
while ( (read = from.read(bf)) != -1) {
textContent.append(new String(bf));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
from.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
String result = new String(textContent);
result = result.trim();
return result;
}
try {
//读文件
InputStream is = new FileInputStream("输入文件路径/文件名");
InputStreamReader isr = new InputStreamReader(is);
String s = null;
int c = 0;
StringBuffer sb = new StringBuffer();
char b[] = new char[1];
try {
while((c = isr.read(b))>0){
sb.append(b,0,c);
}
}
catch (IOException ex) {
}
//写文件
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("输出文件路径/文件名"),"UTF-8");
osw.write(sb.toString());
}
catch (Exception ex) {
ex.printStackTrace();
}
}