Ⅰ C++中如何读取文件内容
两种读取方法,一种是按行读取,一种是按单词读取,具体如下:
1、按照行读取
string filename = "C:\Users\asusa\Desktop\蓝桥\rd.txt";
fstream fin;
fin.open(filename.c_str(), ios::in);
(此处空格一行)
vector<string> v;
string tmp;
(此处空格一行)
while (getline(fin, tmp))
{
v.push_back(tmp);
}
(此处空格一行)
for (auto x : v)
cout << x << endl;
2、按照单词读取
string filename = "C:\Users\asusa\Desktop\蓝桥\rd.txt";
fstream fin;
fin.open(filename.c_str(), ios::in);
(此处空格一行)
vector<string> v;
string tmp;
(此处空格一行)
while (fin >> tmp)
{
v.push_back(tmp);
}
(此处空格一行)
for (auto x : v)
cout << x << endl;
有读取就有写入,下面是写入的方法
//向文件写五次hello。
fstream out;
out.open("C:\Users\asusa\Desktop\蓝桥\wr.txt", ios::out);
(此处空格一行)
if (!out.is_open())
{
cout << "读取文件失败" << endl;
}
string s = "hello";
(此处空格一行)
for (int i = 0; i < 5; ++i)
{
out << s.c_str() << endl;
}
out.close();
Ⅱ java读取text文件为String,如何实现
/**
* 主要是输入流的使用,最常用的写法
* @param filePath
* @return
*/
public static String read(String filePath)
{
// 读取txt内容为字符串
StringBuffer txtContent = new StringBuffer();
// 每次读取的byte数
byte[] b = new byte[8 * 1024];
InputStream in = null;
try
{
// 文件输入流
in = new FileInputStream(filePath);
while (in.read(b) != -1)
{
// 字符串拼接
txtContent.append(new String(b));
}
// 关闭流
in.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return txtContent.toString();
}
Ⅲ 读取xml文件获取String字符串为乱码,怎么解决
1首先打开XML文件
2发现文件中的中文是乱码状态,找到开头的这段代码
<?xml version="1.0" encoding="ISO-8859-1"?>
3将代码修改为<?xml version="1.0" encoding="gb2312" ?>后保存退出,再打开文件
4你会发现之前的乱码已经全部是中文了,可以想如何修改就怎么修改了
5有些文件不支持中文字符,编辑完成后将编码修改成原来的再保存,防止出错。