Java代码无法写入文本文件,

时间:2016-05-06 11:03:42

标签: java read-write

我试图运行一个模拟器,有几个问题,主要是.... - 代码不打印程序末尾的值 - 代码实际上并不创建文件
- 我很累,所以原谅我犯的任何愚蠢的错误或我遗漏的细节。

我搜索了网站,发现了这个

What is the simplest way to write a text file in java

how to write to text file outside of netbeans

我以为我可以编辑第一个链接中的代码为我工作,但这不起作用(这就是你在这里看到的)

第二页看起来更简单,但没有周围的代码所以我不确定上下文是什么以及我将如何实现它

import java.util.Random; 
import java.util.Scanner;

import java.io.*;
/*
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
*/



public class SimClass {  

    public static void main (String[] args) 
    {

        Scanner keyboard = new Scanner(System.in) ; 
        Random randomNumbers = new Random();  
        //create object from random class

        //create self explanaroty input parameters
        int pkt_in_q = 0 ;
        int pkt_dropped = 0;              
        int input  ;
        int output  ;
        int buffer  ; 
        int x ; 

        double y ;  
        //ask for values for buffer size. input rate, output rate

        y = randomNumbers.nextDouble();
        //attempt to assign a random number to the variable and 

        /*here you should get user input.
        buffer size, # of repitions , if 
        */



        //fix this 
        System.out.print("Enter an integer for the input rate ");
            input = keyboard.nextInt(); 


        System.out.print("Enter an integer for the output rate ");
            output = keyboard.nextInt(); 

        System.out.print("What is the buffer size ");
            buffer = keyboard.nextInt(); 




        for (x = 1000000; x >=0 ; x--)
        { /*
            simulate # of packets dropped/in the que,
            create file, write results to file, output results, 
            */        

            if (y > input/(output/buffer))
                { 
                 if (pkt_in_q < buffer)
                    {       
                        pkt_in_q++ ;
                    }
                 else 
                 {
                    pkt_dropped++ ;
                 } 
                 //if statement should terminate here 
                }
            else
             if (pkt_in_q > 0) 
             { 
                pkt_in_q -- ;     
             }


        }


        /*
            create file, write results to file, output results, 
            */  

        try { /*this seeems to be the problem, the program is either not doing
                anything with this or not making the results visible
                        */

            String content =( " pkt_in_q is " + pkt_in_q + 
                    "pkt_dropped is " + pkt_dropped);


                File file = new  File("C:/Temp/inputFile.txt");

                    // if file doesnt exists, then create it
                    if (!file.exists()) 
                    {
                    file.createNewFile();
                    }

                    FileWriter fw = new FileWriter(file.getAbsoluteFile());
                    try (BufferedWriter bw = new BufferedWriter(fw)) 
                    {
                    bw.write(content);
                    bw.close();
                    }

                    System.out.println("packets dropped value is = " +
                           pkt_dropped + "packets in q value is = " + pkt_in_q);

            } 
        catch (IOException e) 
        {
        //e.printStackTrace();
        }   

    }

}

2 个答案:

答案 0 :(得分:0)

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);
    Random randomNumbers = new Random();
    //create object from random class

    //create self explanaroty input parameters
    int pkt_in_q = 0;
    int pkt_dropped = 0;
    int input;
    int output;
    int buffer;
    int x;

    double y;
    //ask for values for buffer size. input rate, output rate

    y = randomNumbers.nextDouble() * 10;
    System.out.println("Y++++++" + y);
    //attempt to assign a random number to the variable and 

    /*here you should get user input.
    buffer size, # of repitions , if 
     */

    //fix this 
    System.out.print("Enter an integer for the input rate ");
    input = keyboard.nextInt();

    System.out.print("Enter an integer for the output rate ");
    output = keyboard.nextInt();

    System.out.print("What is the buffer size ");
    buffer = keyboard.nextInt();

    for (x = 1000000; x >= 0; x--) { /*
                   simulate # of packets dropped/in the que,
                   create file, write results to file, output results, 
     */

        if (y > input / (output / buffer)) {
            if (pkt_in_q < buffer) {
                pkt_in_q++;
            } else {
                pkt_dropped++;
            }
            //if statement should terminate here 
        } else if (pkt_in_q > 0) {
            pkt_in_q--;
        }

    }

    /*
        create file, write results to file, output results, 
     */

    try { /*this seeems to be the problem, the program is either not doing
                   anything with this or not making the results visible
     */

        String content = (" pkt_in_q is " + pkt_in_q + "pkt_dropped is " + pkt_dropped);

        String folderPath = "D:" + File.separator + "Temp";
        String fileName = folderPath + File.separator + "inputFile.txt";
        File folder = new File(folderPath);
        File file = new File(fileName);
        folder.mkdir();
        // if file doesnt exists, then create it
        if (!file.exists()) {
            //file.mkdir();
            file.createNewFile();
            System.out.println("File created");

        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        try {
            bw.write(content);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("packets dropped value is = " + pkt_dropped
                + "packets in q value is = " + pkt_in_q);

    } catch (IOException e) {
        //e.printStackTrace();
    }

}

更正了代码检查,并根据您的要求更改文件目录和文件夹目录。

更正细节:

首先,您无法定义如下所示的试用块

try (BufferedWriter bw = new BufferedWriter(fw)) 

应该定义为

try{
}
catch(IOException e)
{
    //do something
}

修改后的代码如下所示:

FileWriter fw = new FileWriter(file.getAbsoluteFile());
                        BufferedWriter bw = new BufferedWriter(fw);
                        try 
                        {
                        bw.write(content);
                        bw.close();
                        }
                        catch (IOException e) 
                        {
                        //e.printStackTrace();
                        }

其次,您必须先创建目录,然后才能在目录中创建文件。所以只需修改代码即可创建目录并创建文件。

String folderPath = "D:" + File.separator + "Temp";
        String fileName = folderPath + File.separator + "inputFile.txt";
        File folder = new File(folderPath);
        File file = new File(fileName);
        folder.mkdir();         

希望它澄清你的怀疑。

答案 1 :(得分:0)

我认为代码由于文件路径错误而无法执行。

val splitString: (String => Seq[String]) = { s => 
  val seq = s.split(",").map(i => i.trim).toSeq 

  // Remove "u[" from the first element and "]" from the last:
  Seq(seq(0).drop(2)) ++ 
    seq.drop(1).take(seq.length-2) ++ 
      Seq(seq.last.take(seq.last.length-1))
}

import org.apache.spark.sql.functions._
val newDF = df_records
  .withColumn("authors_array", udf(splitString).apply(col("_authors")))

C中没有名为“Temp”的文件夹 开车。如果你手动创建Temp文件夹,那么代码将成功执行。

File file = new  File("C:/Temp/inputFile.txt");

我在D:驱动器中创建了“Temp”文件夹并且代码执行成功。