java 读本地TXT文件,存入内存(不要输出到控制台),然后再生TXT2文件,并写入读的内容
展开全部
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class Test
{
static List<String> list = new ArrayList<String>();
public static void main(String[] args)
{
String readFilePath = "D:\\test.txt";
String writeFilePath = "D:\\test1.txt";
readTxtFile(readFilePath);
writeTxtFile(writeFilePath,list);
}
/**
* 导出到文件
* @param list2
*/
public static void writeTxtFile(String writeFilePath, List<String> list2)
{
FileOutputStream fs;
try
{
fs = new FileOutputStream(new File(writeFilePath));
PrintStream p = new PrintStream(fs);
for(String str:list)
{
p.println(str);
}
p.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
/**
* 导入到内存
* @param filePath
*/
public static void readTxtFile(String readFilePath)
{
try
{
String encoding = "GBK";
File file = new File(readFilePath);
if (file.isFile() && file.exists())
{ // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null)
{
list.add(lineTxt);
}
read.close();
}
else
{
System.out.println("找不到指定的文件");
}
}
catch (Exception e)
{
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询