向txt文件写入内容基本思路就是获得一个file对象,新建一个txt文件,打开I/O操作流,使用写入方法进行读写内容,示例如下:
package common;
import java.io.*;
import java.util.ArrayList;
public class IOTest {
public static void main (String args[]) {
ReadDate();
WriteDate();
}
/**
* 读取数据
*/
public static void ReadDate() {
String url = “e:/2.txt”;
try {
FileReader read = new FileReader(new File(url));
StringBuffer sb = new StringBuffer();
char ch[] = new char[1024];
int d = read.read(ch);
while(d!=-1){
String str = new String(ch,0,d);
sb.append(str);
d = read.read(ch);
}
System.out.print(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 写入数据
*/
public static void WriteDate() {
try{
File file = new File(“D:/abc.txt”);
if (file.exists()) {
file.delete();
}
file.createNewFile();
BufferedWriter output = new BufferedWriter(new FileWriter(file));
ArrayList ResolveList = new ArrayList();
for (int i = 0; i < 10; i++) {
ResolveList.add(Math.random()* 100);
}
for (int i=0 ;i
output.write(String.valueOf(ResolveList.get(i)) + “\n”);
}
output.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
原文出自【比特网】,转载请保留原文链接:http://soft.chinabyte.com/database/303/12439303.shtml
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final int MAX = 10000;
public static final String FILE_PATH = "c:\\content.txt";
public static String[] contents = new String[MAX];
static {
for (int i = 0; i < 10000; i++) {
contents[i] = "" + i;
}
}
public static void main(String[] args) {
FileWriter fw = null;
try {
File f = new File(FILE_PATH);
if (!f.exists())
f.createNewFile();
fw = new FileWriter(FILE_PATH, true);
for (int i = 0; i < 10000; i++) {
String index = "";
int indexLength = String.valueOf(i).length();
for (int j = 0; j < String.valueOf(MAX).length() - indexLength; j++)
index += "0";
index += String.valueOf(i);
fw.write(index + "\t" + contents[i] + LINE_SEPARATOR);
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if (fw != null)
try {
fw.close();
} catch (IOException e) {
throw new RuntimeException("Close Failed");
}
}
}
}
用for循环,每次写入一行
是通过数据库查询出来的数据吗?