android开发如何把字符串保存为txt格式,并存至SD卡?还有读取的问题?
展开全部
/**
* 保存文件
* @param toSaveString
* @param filePath
*/
public static void saveFile(String toSaveString, String filePath)
{
try
{
File saveFile = new File(filePath);
if (!saveFile.exists())
{
File dir = new File(saveFile.getParent());
dir.mkdirs();
saveFile.createNewFile();
}
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write(toSaveString.getBytes());
outStream.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 读取文件内容
* @param filePath
* @return 文件内容
*/
public static String readFile(String filePath)
{
String str = "";
try
{
File readFile = new File(filePath);
if(!readFile.exists())
{
return null;
}
FileInputStream inStream = new FileInputStream(readFile);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = inStream.read(buffer)) != -1)
{
stream.write(buffer, 0, length);
}
str = stream.toString();
stream.close();
inStream.close();
return str;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return null;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
* 保存文件
* @param toSaveString
* @param filePath
*/
public static void saveFile(String toSaveString, String filePath)
{
try
{
File saveFile = new File(filePath);
if (!saveFile.exists())
{
File dir = new File(saveFile.getParent());
dir.mkdirs();
saveFile.createNewFile();
}
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write(toSaveString.getBytes());
outStream.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 读取文件内容
* @param filePath
* @return 文件内容
*/
public static String readFile(String filePath)
{
String str = "";
try
{
File readFile = new File(filePath);
if(!readFile.exists())
{
return null;
}
FileInputStream inStream = new FileInputStream(readFile);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = inStream.read(buffer)) != -1)
{
stream.write(buffer, 0, length);
}
str = stream.toString();
stream.close();
inStream.close();
return str;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return null;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询