【问题标题】:Java Code failing to write to text file,Java 代码无法写入文本文件,
【发布时间】:2016-05-06 11:03:41
【问题描述】:

我正在尝试运行模拟器,但有几个问题,主要是.... - 代码没有在程序结束时打印出值 - 代码实际上并没有创建文件
-我很累,所以请原谅我犯的任何愚蠢的错误或我遗漏的细节。

我已经搜索了这个网站,我找到了这个

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();
        }   

    }

}

【问题讨论】:

  • 您是否尝试过调试您的代码?这比发布到 Stack Overflow 恕我直言更有帮助。
  • 为什么要抑制异常?他们会告诉你出了什么问题。
  • 蒂姆我正在使用netbeans并且代码没有抛出任何错误,“运行”按钮旁边的“调试”选项也是灰色的,表明代码没有错误并且我的错误是合乎逻辑的或组织。 Takeshi,我不确定你指的是什么。请详细说明。我会说我对代码有大约 80% 的理解。多于。就像我说的那样,我从其他地方复制了代码。
  • 你需要了解代码中的try、catch、异常和cmets。 e.printStackTrace() 将显示您遇到的错误,但您正在捕获异常并且不显示任何内容。 e.printStackTrace 被注释掉。

标签: java read-write


【解决方案1】:

我认为由于文件路径错误,代码没有执行。

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

C: 驱动器中没有名为 "Temp" 的文件夹。如果您手动创建 Temp 文件夹,则代码将成功执行。

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

我在D:盘创建了“Temp”文件夹,代码执行成功。

【讨论】:

  • 即使我写到c盘,程序仍然出错(它没有创建java应该写入的文件
  • 你是否在C盘创建了一个名为“Temp”的新文件夹??
【解决方案2】:
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 块

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();         

希望它能澄清你的疑问。

【讨论】:

  • 您能否完整地解释一下您的更改以及我做错了什么?我看到了一些改变,我想确定我理解你做了什么以及为什么
  • "File.separator" 是用于定义文件路径的斜线。 folder.mkdir() 方法用于创建文件夹。
  • 嗯,这很有帮助,代码运行,但在 netbeans 中运行程序后文件未创建。我是否需要从 cmd 运行才能获得所需的结果?特别喜欢用我的计算结果生成一个文件。
  • 它应该创建目录,请检查是否有任何配置错误或导致问题的任何原因。从命令propmpt尝试
  • 我也刚刚注意到,打印语句中的 Y+++++ 也没有出现
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多