简体   繁体   English

Java写入文件不起作用

[英]java writing to a file not working

I was wondering if anyone can take a look at my code and see what i'm doing wrong. 我想知道是否有人可以看一下我的代码,看看我在做什么错。 I'm trying to get my program to write to a file but it wont. 我正在尝试让我的程序写入文件,但不会。 I need some help to get it to write the result to a file. 我需要一些帮助,以将结果写入文件。 Yes i know many questions have been asked about this and yes i looked at them, there's quite a few. 是的,我知道有人问过很多问题,是的,我看着他们,有很多问题。 I just cant really use there examples it doesnt make sense to me. 我只是不能真正使用那里的例子对我来说是没有意义的。 Any help would be great. 任何帮助都会很棒。

import java.util.Scanner;
import java.io.*;

public class DistanceFile {    
    public static void main(String[] args) throws IOException {
        int time; //hours traveled
        int hour;//for the formula
        String FileName;
        Scanner scanner= new Scanner(System.in);
        System.out.println("Enter the speed of the vehicle");
        int speed= scanner.nextInt();
        while (speed<=0){
            System.out.println("Please enter a valid speed");
            speed=scanner.nextInt();
        }
        System.out.println("Enter the number of hours traveled");
        time=scanner.nextInt();
        while (time<=0){
            System.out.println("Please enter a valid time");
            time=scanner.nextInt();
        }
        hour=0;

        PrintWriter outputFile= new PrintWriter("DistanceFile.txt");
        for(  hour = 1; hour <= time; hour++)
            System.out.println(hour+ " " + (hour * speed));
        outputFile.print(speed+"");
        outputFile.print(time+" ");
        outputFile.close();

Your code is working fine. 您的代码运行正常。 You should enter the whole file path like: 您应该输入整个文件路径,例如:

PrintWriter outputFile= new PrintWriter("C:\\Users\\XXX\\Desktop\\test.txt");

Check out the BufferedWriter . 签出BufferedWriter

Even after tweaking your code it still doesn't work, check if the place you're saving at can be written to. 即使在调整代码后仍然无法正常工作,请检查保存位置是否可以写入。 If your program is not allowed to, you could save in a different place or modify the folder settings. 如果不允许您的程序,则可以将其保存在其他位置或修改文件夹设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM