Ⅰ 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有些文件不支持中文字元,編輯完成後將編碼修改成原來的再保存,防止出錯。