代码已写好,希望对你有帮助,顺便求好评。
package architecture;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author Wang Zhenhui
* @blog www.soaringroad.com
启谈*
*/
public class AboutIOReaderWriter {
/**
* main
* @param args
*/
public static void main(String[] args) {
String filePath = "d:\\out2.txt";
write(filePath);
read(filePath);
}
/**
* Read
* @param filePath file path
*/
public static void read(String filePath) {
FileReader fr = null;
StringBuilder result = new StringBuilder();
;
try {
fr = new FileReader(new File(filePath));
char[] charArray = 此旁燃new char[1024];
while (fr.read(charArray) != -1) {
result.append(charArray);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(result.toString());
}
/**
* Write
* @param filePath file path
*/
public static void write(String filePath) {
FileWriter fw = null;
try {
fw = new FileWriter(new File(filePath));
for (int i = 1; i <= 50; i++) {
fw.append(String.valueOf(i));
}
fw.flush();
} catch (IOException e) {
e.printStackTrace();
}
if 森虚(fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
java中实现字符流的写入写出穗山使用BufferedReader和BufferedWriter来实现,具体事例代码如下:
public class FileTest { public static void main(String[] args) { File file=new File("C:\\Users\\hp\\Desktop\梁族坦\a.txt"); BufferedReader read=null; BufferedWriter writer=null; try { writer=new BufferedWriter(new FileWriter("C:\\Users\\橡桐hp\\Desktop\\b.txt")); } catch (IOException e1) { e1.printStackTrace(); } try { read=new BufferedReader(new FileReader(file)); String tempString = null; while((tempString=read.readLine())!=null){ writer.append(tempString); writer.newLine();//换行 writer.flush();//需要及时清掉流的缓冲区,万一文件过大就有可能无法写入了 } read.close(); writer.close(); System.out.println("文件写入完成..."); } catch (IOException e) { e.printStackTrace(); } }}
这样就实现了指定读取一个目录下的文件的内容写入到指定目录下的文件中。
FileWriter fw = new FileWriter("D:\\number.txt");
for (int i = 1; i <= 50; i++) {
// fw.write(String.valueOf(i)+"局带 ");
fw.write(i+" ");
}
fw.flush();
fw.close();
FileReader fr = new FileReader("D:\\number.txt"桐知芦);
BufferedReader br=new BufferedReader(fr);
String ss;
while ((ss=br.readLine())!=null){
System.out.println(ss);
}
br.close();
最简单就是猛芹这样了。