java编程:从一个名为file的文件中逐行读取然后将读取的内容放进另一个文件file1中。

2024-11-17 16:53:12
推荐回答(3个)
回答1:

/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*
* @param fileName
* 文件名
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 文件写入
*
* @param filePath 路径名称
* @param sb 要写入的字符
*/
public void writeFromBuffer(String filePath, String sb)throws IOException {
File file = new File(filePath);
FileWriter fw;
try {
fw = new FileWriter(file);
if (sb.toString() != null && !"".equals(sb.toString())) {
fw.write(sb.toString());
}
fw.close();
} catch (IOException e) {
throw new IOException("文件写入异常!请检查路径名是否正确!");
}

}

自己组织一下,读取的数据可以放在stringbuffer里然后在传给写入方法

回答2:

MenuTreeInfoForm menuInfo = (MenuTreeInfoForm)form;
FormFile file = menuInfo.getFile();

InputStream ips = new FileInputStream( "" );
Workbook rwb = Workbook.getWorkbook(ips);
Sheet st = rwb.getSheet(0);
List infoList = new ArrayList();
List infoArrList = new ArrayList();

for(int i = 0; i < st.getRows(); i++) {

String name= st.getCell(0, i).getContents().trim();
String age = st.getCell(1, i).getContents().trim();
String sex = st.getCell(2, i).getContents().trim();

infoArrList.add(0, name);
infoArrList.add(1, age);
infoArrList.add(2, sex);
infoList.add(i,infoArrList);
}

//写如文件
OutputStream ops = new FileOutputStream("D:\test");
try {
WritableWorkbook wwb = Workbook.createWorkbook(ops);
WritableSheet ws = wwb.createSheet("new sheet", 0);
// 设定指定列的宽度
ws.setColumnView(0, 15);
ws.setColumnView(1, 15);
ws.setColumnView(2, 15);
ws.setColumnView(3, 15);
// 设定标签颜色
WritableFont wf_merge = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.NO_BOLD, false,UnderlineStyle.SINGLE_ACCOUNTING, Colour.RED);
WritableCellFormat wff_merge = new WritableCellFormat(wf_merge);
wff_merge.setBackground(Colour.WHITE);
// 设置首行标题栏
Label label00 = new Label(0, 0, "操作状态", wff_merge);
ws.addCell(label00);
Label label10 = new Label(1, 0, "帐号", wff_merge);
ws.addCell(label10);
Label label20 = new Label(2, 0, "密码", wff_merge);
ws.addCell(label20);
Label label30 = new Label(3, 0, "sip", wff_merge);
ws.addCell(label30);

int infoListSize = infoList.size();
UpLoadInfo upLoadInfo = null;
if(infoListSize>0){
for (int i = 1; i <= infoListSize; i++) {
List list = infoList.get(i-1);
for(int j = 1; j <= infoArrList.size(); j++){
ws.addCell(new Label(j, j, infoArrList.get(j)));
}
}
}
wwb.write();
wwb.close();
ops.close();
}catch (Exception e) {

}

回答3:

网上应该很多啊