将字符串写入文件:
- import java.io.*;
- class FileOutputDemo {
- public static void main(String args[]) {
- FileOutputStream out; // declare a file output object
- PrintStream p; // declare a print stream object
- try {
- // connected to "myfile.txt "
- out = new FileOutputStream("C:/a.txt");
- // Connect print stream to the output stream
- p = new PrintStream(out);
- p.println("This is written to a file ");
- p.close();
- } catch (Exception e) {
- System.err.println("Error writing to file ");
- }
- }
- }
java读取文件内容:
- import java.io.*;
- class FileInputDemo {
- public static void main(String args[]) {
- // args.length is equivalent to argc in C
- try {
- // Open the file that is the first command line parameter
- FileInputStream fstream = new FileInputStream("C:/b.txt");
- // Convert our input stream to a DataInputStream
- DataInputStream in = new DataInputStream(fstream);
- // Continue to read lines while there are still some left to
- // read
- String s = "";
- while (in.available() != 0) {
- // Print file line to screen
- s=in.readLine();
- System.out.println(s);
- }
- // String regex="src=/"";
- // s=s.replaceAll(regex,"str=/"http://article.star.com:8081/temp/");
- in.close();
- } catch (Exception e) {
- System.err.println("File input error ");
- }
- }
- }