如何使用Java逐行写入文件内容

huangapple go评论75阅读模式
英文:

How to write the content Line by Line in a file using java

问题

以下是翻译好的代码部分:

public static void main(String args[]) throws FileNotFoundException, IOException {
    HashSet<Integer> newset = new HashSet<Integer>();
    
    FileOutputStream fo = null;
    
    for(int i = 0; i < 100; i++){
        double d = Math.random() * 10000;  
        //System.out.println(d);
        String random_no = Integer.toString((int)d);
        newset.add((int)d);
        
        fo = new FileOutputStream("E:\\Test\\Files\\Test_No.txt", true); // 追加模式
        fo.write((random_no + "\n").getBytes()); // 写入并换行
    }
    fo.close();
    System.out.println("Size is : " + newset.size());
}

请注意,我在FileOutputStream的构造函数中添加了参数true,以便在每次写入时都以追加模式打开文件,并且我在fo.write中添加了\n来在每次写入后换行。这样可以确保每个随机数都会被逐行写入到文本文件中。

英文:

How do i write all the ouputs line by line in a txt file? the below snippet is writing only 1 line. Basically i want random_no to be written line by line in txt file.

public static void main(String args[]) throws FileNotFoundException, IOException {
    HashSet &lt;Integer&gt; newset = new HashSet &lt;Integer&gt;();
    
    FileOutputStream fo = null;
    
    for(int i =0;i&lt;100;i++){
        double d=Math.random()*10000;  
        //System.out.println(d);
        String random_no= Integer.toString((int)d);
        newset.add((int)d));
        
        fo = new FileOutputStream(&quot;E:\\Test\\Files\\Test_No.txt&quot; ); 
        fo.write(random_no.getBytes();
        
        
        
    }
    fo.close();
	System.out.println(&quot;Size is : &quot; +newset.size());

答案1

得分: 1

public static void main(String[] args) throws IOException {
FileOutputStream fo = new FileOutputStream("D:\Test_No.txt");
HashSet newset = new HashSet();
for (int i = 0; i < 100; i++) {
double d = Math.random() * 10000;
String random_no = Integer.toString((int) d);
newset.add((int)d);
fo.write(random_no.getBytes());
fo.write("\n".getBytes());
}
fo.close();
}

英文:

Here you need to do two things:

a) Open file outside the loop

b) Write newline after every number

public static void main(String[] args) throws IOException {
		FileOutputStream fo = new FileOutputStream(&quot;D:\\Test_No.txt&quot;);
		 HashSet&lt;Integer&gt; newset = new HashSet &lt;Integer&gt;();
		for (int i = 0; i &lt; 100; i++) {
			double d = Math.random() * 10000;
			// System.out.println(d);
			String random_no = Integer.toString((int) d);
			newset.add((int)d);
			fo.write(random_no.getBytes());
			fo.write(&quot;\n&quot;.getBytes());
		}
		fo.close();

}

答案2

得分: 0

你在循环内部打开文件,尝试:

public static void main(String args[]) throws FileNotFoundException, IOException {
    HashSet<Integer> newset = new HashSet<Integer>();
    FileOutputStream fo = new FileOutputStream("E:\\Test\\Files\\Test_No.txt");
    for (int i = 0; i < 100; i++) {
        double d = Math.random() * 10000;
        //System.out.println(d);
        String random_no = Integer.toString((int) d) + System.lineSeparator();
        newset.add((int) d);
        fo.write(random_no.getBytes());
    }
    fo.close();
    System.out.println("Size is: " + newset.size());
}

你还可以考虑自动处理关闭:

public static void main(String args[]) throws FileNotFoundException, IOException {
    HashSet<Integer> newset = new HashSet<Integer>();
    try (FileOutputStream fo = new FileOutputStream("E:\\Test\\Files\\Test_No.txt")) {
        for (int i = 0; i < 100; i++) {
            double d = Math.random() * 10000;
            //System.out.println(d);
            String random_no = Integer.toString((int) d) + System.lineSeparator();
            newset.add((int) d);
            fo.write(random_no.getBytes());
        }
    }
    System.out.println("Size is: " + newset.size());
}
英文:

You're opening the file inside the loop, try:

public static void main(String args[]) throws FileNotFoundException, IOException {
    HashSet &lt;Integer&gt; newset = new HashSet &lt;Integer&gt;();
    FileOutputStream fo = new FileOutputStream(&quot;E:\\Test\\Files\\Test_No.txt&quot; );
    for(int i =0;i&lt;100;i++){
        double d=Math.random()*10000;  
        //System.out.println(d);
        String random_no= Integer.toString((int)d) + System.lineSeparator();
        newset.add((int)d);
        fo.write(random_no.getBytes());
    }
    fo.close();
    System.out.println(&quot;Size is : &quot; +newset.size());
}

You might also want to consider handling the close automatically:

public static void main(String args[]) throws FileNotFoundException, IOException {
    HashSet &lt;Integer&gt; newset = new HashSet &lt;Integer&gt;();
    try (FileOutputStream fo = new FileOutputStream(&quot;E:\\Test\\Files\\Test_No.txt&quot; )) {
        for(int i =0;i&lt;100;i++){
            double d=Math.random()*10000;  
            //System.out.println(d);
            String random_no= Integer.toString((int)d) + System.lineSeparator();
            newset.add((int)d);
            fo.write(random_no.getBytes());
        }
    }
    System.out.println(&quot;Size is : &quot; +newset.size());
}

答案3

得分: 0

`FileOutputStream` 应该在循环之外进行初始化

此外要打印新行您还可以使用 `BufferedWriter` 而不是 `FileOutputStream`。

`BufferedWriter` 提供了 `BufferedWriter.newLine()` 选项该选项可以独立于环境WindowsUnix 等处理换行
```java
    public static void main(String args[]) throws IOException {
        HashSet<Integer> newset = new HashSet<>();
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("Test_No.txt", true));
        for (int i = 0; i < 100; i++) {
            double d = Math.random() * 10000;
            String random_no = Integer.toString((int) d);
            newset.add((int) d);
            bufferedWriter.write(random_no);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
        System.out.println("Size is: " + newset.size());
    }
英文:

FileOutputStream should be initialised outside the loop.

Also, to print new line, you can also use BufferedWriter instead of FileOutputStream.

BufferedWriter gives you option of BufferedWriter.newLine() which would handle new lines independent of the environment(windows, unix, etc.).

    public static void main(String args[]) throws IOException {
        HashSet&lt;Integer&gt; newset = new HashSet&lt;&gt;();
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(&quot;Test_No.txt&quot;, true));
        for (int i = 0; i &lt; 100; i++) {
            double d = Math.random() * 10000;
            String random_no = Integer.toString((int) d);
            newset.add((int) d);
            bufferedWriter.write(random_no);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
        System.out.println(&quot;Size is : &quot; + newset.size());
    }

huangapple
  • 本文由 发表于 2020年8月17日 18:55:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63449449.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定