java编程将一个99乘法表输出到文件中

如题所述

package controller;

import java.io.*;


public class IODemo {


public static void main(String[] args)throws IOException {

File file = new File("d:/九九乘法表.txt");

OutputStream output = new FileOutputStream(file);

String str = "";

for(int i=1;i<10;i++){

for(int j=1;j<=i;j++){

str+=j+"*"+i+"="+i*j+"\t";

}

str+="\r\n";

}

System.out.println(str);

output.write(str.getBytes());

System.out.println("写入成功!");

//不用了记得关掉

output.close();

}

}

温馨提示:内容为网友见解,仅供参考
第1个回答  2012-04-20
完全满足你的需求,而且代码很简单

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFile {

public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer("九九乘法表:\r\n");
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
stringBuffer.append(i+"*"+j+"="+i*j+" ");
}
stringBuffer.append("\r\n");
}
String str = stringBuffer.toString();
System.out.println(str);
File txt=new File("d:\\九九乘法表.txt");
if(!txt.exists()){
try {
txt.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
byte bytes[]=new byte[512];
bytes=str.getBytes();
int b=str.length();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(txt);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes,0,b);
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
第2个回答  推荐于2017-10-11
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class Admin {

public static void main(String[] args) {
List result = new ArrayList();
for (int i = 1; i <= 9; i++) {
for (int j = i; j <= 9; j++) {
System.out.print(i + "*" + j + "=" + i * j);
System.out.print(" ");
result.add(i + "*" + j + "=" + i * j + " ");
}
System.out.println();
result.add("\r\n");
}
saveToFile(result);
}

private static void saveToFile(List result) {
File f = new File("d:/a.txt");
FileWriter fw = null;
try {
fw = new FileWriter(f);
for (int i = 0; i < result.size(); i++) {
fw.write(String.valueOf(result.get(i)));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
}本回答被网友采纳
第3个回答  2011-08-09
用一个FOR循环和文件复制方法
相似回答