如何使用java在文本文件上写内容?

时间:2010-12-06 01:21:55

标签: java file


我在java.which system.out中有一个程序,一些字符串,我需要将它们中的每一个保存在文本文件中 它以格式显示 ruo1 row2 row3
我想要它 ROW1
2行
ROW3
我怎么能在java中做到这一点?

import java.util.Arrays;
import java.io.*;
public class BruteForce {
 public static FileOutputStream Output;
    public static PrintStream file;
    public static String line;

public static void main(String[] args) {
String password = "javabeanc";
char[] charset = "abcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 8);

String attempt = bf.toString();
while (true) {
    FileWriter writer;
    try {
      writer = new FileWriter("test.txt");

        writer.write(attempt+"\n");

      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }


attempt = bf.toString();
System.out.println("Tried: " + attempt);

bf.increment();
}
}


private char[] cs; // Character Set
private char[] cg; // Current Guess

public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}

public void increment() {
int index = cg.length - 1;
while(index >= 0) {
if (cg[index] == cs[cs.length-1]) {
if (index == 0) {
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}

public String toString() {
return String.valueOf(cg);
}
}

3 个答案:

答案 0 :(得分:6)

非常快速的代码。如果有编译错误,我道歉。

 import java.io.FileWriter;
  import java.io.IOException;  
  public class TestClass {
      public static String newLine = System.getProperty("line.separator");
      public static void main(String[] a) {
        FileWriter writer;
        try {
          writer = new FileWriter("test.txt");
          for(int i=0;i<3;i++){
            writer.write(row+i+newLine);
          }
          writer.close();
        } catch (IOException e) {
          e.printStackTrace();
        }

      }
    }

答案 1 :(得分:0)

如何为每一行添加换行符“\ n”?

答案 2 :(得分:0)

你可以使用PrintWriter pw;
 pw.println(行+ I) 在上面而不是硬编码newLine