java保存文件的代码 java如何保存文件( 二 )


import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class Fileout1 {
public static void main(String[] args){
try {
File file = new File("File.txt");
Scanner num = new Scanner(System.in);
System.out.println("请输入要录入java保存文件的代码的内容java保存文件的代码:");
String b = num.nextLine();
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(b);
writer.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
输出的文件在工作空间的工程文件夹里
用Java读取TXT文件和存入TXT文件的代码/****************
* 文件读取与保存
*
* @author Administrator
*
****************/
public class FileOption {
/**
【java保存文件的代码 java如何保存文件】* 根据路径读取文件
*
* @param readPath
*读取文件的路径
* @return
* @throws Exception
*/
public String readFile(String readPath) throws Exception {
return readFile(new File(readPath));
}
/**
* 读取文件
*
* @param file
* @return
* @throws Exception
*/
public String readFile(File file) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuffer sbf = new StringBuffer("");
String line = null;
while ((line = br.readLine()) != null) {
sbf.append(line).append("\r\n");// 按行读?。芳踊恍衆r\n
}
br.close();
return sbf.toString();
}
/**
* 写入文件
*
* @param str
*要保存的内容
* @param savePath
*保存的文件路径
* @throws Exception
*找不到路径
*/
public void writeFile(String str, String savePath) throws Exception {
BufferedWriter bw = new BufferedWriter(new FileWriter(savePath));
bw.write(str);
bw.close();
}
public static void main(String[] args) {
FileOption fop = new FileOption();
String filePath = "d:/derby.log";
String str = null;
try {
str = fop.readFile(filePath);
System.out.println(str);
} catch (Exception e) {
System.out.println("文件不存在");
}
String savePath = "d:/derby.log.bak";// 将上一个读取的文件另存一份
try {
fop.writeFile(str, savePath);
} catch (Exception e) {
System.out.println("保存文件失败(路径错误)");
}
}
}
JAVA编程问题 如何改写一个文件并保存? 要求完整代码假定开始没有这个文件java保存文件的代码,在插入数据时建立文件 。
FILE *fp;
fopen(激法馆盒弋谷龟贪骇楷"c:\\a.txt","wt+");这个是打开以写或读的方式打开文件 。打开后就可以写入java保存文件的代码了,用for循环,例如你有4组数据,
for(int i;i=4;i++)
{
fprintf(fp,"%s%s%s%s",a,b,c,d);
}
fprintf();就实现了把数据写入文件的功能 。跟printf();差不多 , 只是一个是往文件里写 , 一个是往屏幕上写 。
上面就实现了插入操作 。
如果你想删除一个数据,就先在数组中删除,然后重新进行上述写入文件操作 。要是读取数据的话就在打开文件时:fp = fopen("c:\\a.txt",r+);
要是还不明白的话就看下书,这两个函数就可以满足你的需要 。
java如何保存文件这是我原来做的例子,里面有文件储存的内容,代码不多,给你参考参考.
/**
* 五个按钮的故事,西西哈 。
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class FileMessage extends Frame implements ActionListener
{