#file input and output

1 messages · Page 1 of 1 (latest)

undone timber
#

I can't seem to work this out with file .in and file .out

hallow elbowBOT
#

<@&987246399047479336> please have a look, thanks.

undone timber
#

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
public static int digits(int n){
int nrdigits=0;
while(!(n/10+n%10==0)){
n=n/10;
nrdigits++;
}
return nrdigits;
}
public static void main(String[] args) {
int n=0, k, i =0,rez=0,nrdigits;
try{
File inputfile = new File("magnitudine.in");
Scanner user_input = new Scanner(inputfile);

        n = user_input.nextInt();
        k= user_input.nextInt();
    }catch (FileNotFoundException e){
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
    nrdigits = digits(n);
    int temp = n;
    int[] digits = new int[nrdigits];
    while(i<nrdigits){
        digits[i]=temp%10;
        temp= temp%10;
        i++;
    }
    Arrays.sort(digits);
    int diff = digits[nrdigits-1] - digits[0];
    rez=diff;


    try {
        FileWriter myWriter = new FileWriter("magnitudine.out");
        myWriter.write(rez);

        myWriter.close();
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

}

ancient minnow
#

why not using nio instead of io?

undone timber
#

idk

#

i just searched on google

#

An error occurred.
java.io.FileNotFoundException: magnitudine.in (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.base/java.util.Scanner.<init>(Scanner.java:645)
at Main.main(Main.java:21)

#

this the error

hallow elbowBOT
#

File IO in Java should be done preferably with NIO (Java 7+), revolving around the classes Files and Path; and not with the old interface File, BufferedReader, FileReader and similar.

NIO is simple to use. The path to a file is represented using the Path class:

Path path = Path.of("myFile.txt");

All file operations can be found in the Files class:

// Reading
List<String> allLines = Files.readAllLines(path);
// or as a single string
String content = Files.readString(path);
// or with a stream
try (Stream<String> stream = Files.lines(path)) {
  stream.forEach(System.out::println);
}

// Writing
Files.write(path, lines);
// or as a single string
Files.writeString(path, "hello world");
// or with extra options
Files.writeString(path, "hello world",
  StandardOpenOption.WRITE,
  StandardOpenOption.CREATE,
  StandardOpenOption.APPEND);

If you need more control over the process, you can fallback to the old interface, but prefer using the bridge methods from NIO (Files.newBufferedReader, Files.newInputStream, path.toFile() and similar) to benefit from advantages such as correct encoding and better error detection.

Here is a simple example of how to read a file line-wise with the old interface

try (BufferedReader br = Files.newBufferedReader(path)) {
  String line;
  while ((line = br.readLine()) != null) {
    System.out.println(line);
  }
}

it is way more verbose than NIO but it gives more control.

You must not forget to close file handles, even in all exceptional cases. Closing a handle manually is very hard, which is why you should always use try-with-resources for this to let Java automatically close the handle for you:

try (SomeResource resource = ...) {
  ...
} // Automatically closed here, even in exceptional cases
undone timber
#

so you think that would work

#

let me adjust my code

ancient minnow
#

that might not fix your problem, but its def. better code

undone timber
#

ok but I want to understand why is it giving me that error

#

i will try to do it this way and see

#

what if it works

ancient minnow
undone timber
#

that i understood

#

but my file exists

ancient minnow
#

the problem is the location

#

you using intellijs build system

#

I am not sure how its compiling that

#

but if you use maven/gradle you have a different structure

#

with a dedicated resources folder

undone timber
#

aha thx

#

i moved the in file out of src

#

and now it works

#

i have one more question

#

in the path thingie

#

can I create a file with that

ancient minnow
#

also why is the file ending in .in?

undone timber
#

or is it only read

ancient minnow
undone timber
undone timber
#

thing you said to me with the bot

undone timber
ancient minnow
#

you can create files as well

undone timber
#

aha thanks

ancient minnow
#

Path path = Path.of(filename)
and then some helper method of Files.java

#

let me find it real quick

undone timber
#

thx

velvet ledgeBOT
#
public static Path createFile(
  Path path,
  FileAttribute<? extends >... attrs
) throws IOException

Creates a new and empty file, failing if the file already exists. The check for the existence of the file and the creation of the new file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory.

The attrs parameter is optional file-attributes to set atomically when creating the file. Each attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

ancient minnow
#

Files.createFile(path)

undone timber
#

ok tgx

#

and the exception handling

#

is the same

ancient minnow
#

might be different at some points

undone timber
#

aha

#

ok still

#

thx for help