mashen08.09整理今日所学

来源:互联网 发布:银行程序员怎么样 编辑:程序博客网 时间:2024/05/02 23:21

1.将123.txt与456.txt这2个文件合并到第三个文件789.txt中

import java.io.*;
public class IO_Test {
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("e:/123.txt");
byte[] b = new byte[200];
int length = 0;
String s = null;
//文件123的内容
StringBuffer sb1 = new StringBuffer();
//读取123文件内容
while (-1 != (length = is.read(b))) {
s = new String(b, 0, length);
sb1.append(s);
}
//读取文件456内容
InputStream ins = new FileInputStream("e:/456.txt");
byte[] by = new byte[200];
int len = 0;
//文件456内容
StringBuffer sb2 = new StringBuffer();
while (-1 != (len = ins.read(by))) {
String st = new String(by, 0, len);
sb2.append(st);
}

//创建文件789.txt
File file1 = new File("e:/789.txt");
if (!file1.exists()) {
file1.createNewFile();
}
sb1.append(sb2);
String context = sb1.toString();

OutputStream ops = new FileOutputStream(file1);

//写入合并后内容
ops.write(context.getBytes());
ops.flush();
ops.close();
ins.close();

}
}


2.将99乘法表放入a.txt中

public class TestTable {
public static void main(String[] args) throws IOException {
/*
  99乘法表放入文件a.txt中
*/
String s = null;
StringBuffer sb = new StringBuffer();
for(int x =1; x< 10; x++){
for(int y = 1; y<= x; y++){
s = new String(x+"*"+y+"="+x*y+"\t");
sb.append(s);
}
sb.append("\n");
}
String context = sb.toString();
File fl = new File("e:\\a.txt");
if(!fl.exists()){
fl.createNewFile();
}
OutputStream os = new FileOutputStream(fl);
os.write(context.getBytes());

}
}

0 0
原创粉丝点击