如何将一个数组中的内容读入到一个新建的文件中?

scholes3232 2003-10-17 01:46:10
将数组中的每个元素读入文件中的并每个元素为一行!
...全文
96 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
scholes3232 2003-10-20
  • 打赏
  • 举报
回复
在我的源文件中的内容后面时候空格的,比如 aaa ,bbb ,...这样的情况,如何能在数组中让这些数据去掉后面的空格,结果就是:array1[aaa,bbb,...];
whywzf 2003-10-20
  • 打赏
  • 举报
回复
for (int i=0;i<array1.length;i++){
array1[i] = array1[i].trim();
}
whywzf 2003-10-17
  • 打赏
  • 举报
回复
不要去new file 就可以了,事先建立好目录和文件。直接打开去写就行了。
我这里每次都new了一个,当然上次的就不见了。
beming 2003-10-17
  • 打赏
  • 举报
回复
RandomAccessFile raf = new RandomAccessFile("yourfile", true);

raf.write(String.getBytes("gb2312"));
raf.close();

或者:

try{
FileOutputStream cLog = new FileOutputStream( "yourfile", true );
cLog.write( sLog.getBytes("gb2312") );
}catch(IOException e){
System.out.println(e.getMessage());
}
scholes3232 2003-10-17
  • 打赏
  • 举报
回复
to beming(Aming):
有没有具体的代码?
谢了!
beming 2003-10-17
  • 打赏
  • 举报
回复
哦,如果你不想覆盖以前的内容,你应该用RandomAccessFile这个类,具体方法你看api doc你就知道了

很简单的
beming 2003-10-17
  • 打赏
  • 举报
回复
如果你的数组元素比较多的话,楼上的不好,

for(int i = 0; i < s.length; i++) {
String ColName = s[i];
sCol += ColName + "\r\n";
}


这里应该使用StringBuffer来处理
scholes3232 2003-10-17
  • 打赏
  • 举报
回复
为什么我每次写入到文件中的内容都会覆盖以前的内容呢?
metome 2003-10-17
  • 打赏
  • 举报
回复
我将 whywzf(古风)的代码做了修整,下面是一个完整的例子。

import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWrite {

public static void main(String[] args)
{
File file=new File("D:/test/");

if (!file.exists()) {
file.mkdirs();
}
file =new File("D:/test/test.txt");
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
e.printStackTrace();
}

String[] s ={"aaaa","bbbb","cccc"};
String sCol="";

for(int i = 0; i < s.length; i++) {
String ColName = s[i];
sCol += ColName + "\r\n";
}

try {
out.write(sCol);
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
whywzf 2003-10-17
  • 打赏
  • 举报
回复
File file=new File(//your path);
if(!file.exists())
file.mkdirs();
file =new File(//your path and file name);
if(!file.exists())
file.createNewFile();

BufferedWriter out = new BufferedWriter(new FileWriter(file));
String[] s ={//your string init};
String sCol="";
for(int i=1;i<=s.length;i++){
String ColName = s[i];
sCol += ColName + "\r\n";
}
out.write(sCol);
out.newLine();
out.close();
qixin_lover 2003-10-17
  • 打赏
  • 举报
回复
File currentfile = new File("文件路径\文件名");
FileWriter outfile = new FileWriter(currentfile );

数组a[i]循环
outfile.write(a[i]);
outfile.write("\n");

outfile.close();
scholes3232 2003-10-17
  • 打赏
  • 举报
回复
to:beming(Aming)
将Stringbuffer中的内容读入文件中是用什么函数?
beming 2003-10-17
  • 打赏
  • 举报
回复
将数组的元素读到StringBuffer里面写对文件中就可以啦

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧