请问如何将整个文件内容读到一个字符串中去?

dgsrest 2003-10-10 12:28:55
有没有详细代码阿
...全文
114 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sxdtwp 2003-10-10
  • 打赏
  • 举报
回复
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

string ReadFileIntoStr()
{
ifstream ifile( "filename" );
ostringstream buffer;

char ch;
while ( buf && ifile.get(ch) )
{
buf.str();
}
retrun buf.str();
}

int main()
{
string text = ReadFileIntoStr();
.....
retrun 0;
}
以上是c++ primer 上的源码,你不妨试试。
207 2003-10-10
  • 打赏
  • 举报
回复

Reader rd=new FileReader(文件名);
String strIn=FileIO.readerToString(strIn);

//读取Reader的全部内容
public static String readerToString(Reader rd) throws IOException{
StringBuffer sbTmp=new StringBuffer();
char[] b= new char(BLKSIZ);
int n;

while((n=rd.read(b))>0){
sb.append(b,0,n);
}

return sbTmp.toString();
}

//读取输入流的内容
public static String inputStreamToString(InputStream isInputStream) throws IOException{
return readerToString(new InputStreamReader(isInputStream));
}
stonegump 2003-10-10
  • 打赏
  • 举报
回复
直接读文件,再写到串里就行了。
private static String getInfo(String tmpFile) throws IOException {
StringBuffer sbFile;
FileReader in = new FileReader(tmpFile);
char[] buffer = new char[4096];
int len;
sbFile = new StringBuffer();
while ( (len = in.read(buffer)) != -1) {
String s = new String(buffer, 0, len);
sbFile.append(s);
}
return sbFile.toString();
}
207 2003-10-10
  • 打赏
  • 举报
回复
这情况一般不用吧

CoolAbu 2003-10-10
  • 打赏
  • 举报
回复
RandomAccessFile fin=new RandomAccessFile(Filename,"r");
String rLine;
long filePointer=0;
long length=fin.length();
while(filePointer<length)
{
rLine=fin.readLine();
stfContent.append(rLine);
filePointer=fin.getFilePointer();
}
fin.close();

String modContent=stfContent.toString();

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧