#LIBRARY java.io.*

1 messages · Page 1 of 1 (latest)

sage bobcat
#

How does all the library java.io works, and how it is used for?

fallen larkBOT
#

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

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

The java.io library in Java provides classes for input and output operations. It is used for reading and writing data to and from various sources such as files, streams, and network connections.

Here are some key classes and their uses from the java.io library:

  1. File: This class represents a file or directory on the file system. It provides methods to create, delete, rename, or check properties of a file/directory.

  2. FileInputStream/FileOutputStream: These classes are used to read/write data from/to a file in byte-oriented manner. They provide methods like read(), write(), close(), etc.

  3. FileReader/FileWriter: These classes are used to read/write data from/to a file in character-oriented manner. They provide methods like read(), write(), close(), etc.

  4. BufferedReader/BufferedWriter: These classes provide buffering capabilities while reading/writing data from/to a file or any other source. They improve performance by reducing the number of I/O operations.

  5. InputStreamReader/OutputStreamWriter: These classes are used for reading/writing character streams using byte streams. They convert bytes to characters (and vice versa) using specified character encoding.

  6. ByteArrayInputStream/ByteArrayOutputStream: These classes allow reading/writing data from/to an in-memory byte array instead of a physical file.

  7. DataInputStream/DataOutputStream: These classes provide methods for reading/writing primitive data types (int, float, boolean, etc.) from/to an input/output stream.

  8. ObjectInputStream/ObjectOutputStream: These classes are used for serializing/deserializing Java objects into/from an input/output stream.

These are just a few examples of the many classes available in the java.io library that cater to different I/O needs in Java programming. By utilizing these classes effectively, you can perform various input/output operations efficiently within your Java programs.

thick pier
#

but nowadays you should use nio instead

#

aka new io

#

also the bot gave a good overview

slim mango
#

I think Files class is pretty op

thick pier
#

yeah, if working with Files ofc

#

InputStream/OutputStream can be used for many things

sage bobcat
vivid zephyr
#

depends on ur pov

#

its technically better and provides non blocking io on the low level

#

but thats not interesting for most users

#

what most users will care about is the end user interface

#

i. e. Files + Path vs the old legacy File class

#

and former is just better in any way

#

less confusing, more convenience, better error handling,...

grand falcon
fallen larkBOT
#

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
sage bobcat
#

Is this right for the read of a basic txt

import java.io.*;
import java.io.IOException;

public class Main {
public static void main(String[] args) {
try {
FileReader reader;
reader = new FileReader("FileName.txt");
int data = reader.read();
while(data != -1){
System.out.print((char)data);
data = reader.read();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

thick pier
#

just use Files.readAllLines instead

#

which gives you a List<String>

sage bobcat
flat sierraBOT
#
public static String readString(Path path) throws IOException

Reads all content from a file into a string, decoding from bytes to characters using the UTF-8 charset. The method ensures that the file is closed when all content have been read or an I/O error, or other runtime exception, is thrown.

This method is equivalent to: readString(Path, Charset)readString(path, StandardCharsets.UTF_8).

cinder spear
#

@sage bobcat use this

sage bobcat
sage bobcat
#

@cinder spear i did this but its not all correct
import java.io.*;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
public static void main(String[] args) {
String FinalString = null;
try {
FinalString = readString(Paths.get("FileName.txt"));
System.out.print(FinalString);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(FinalString);
}
public static String readString(Path path) throws IOException{

    try(FileReader reader = new FileReader(path.toFile())) {
        int data = reader.read();
        while(data != -1){
            System.out.print((char)data);
            StringBuilder.append((char) data);
            data = reader.read();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return StringBuilder.toString();
}

}

cinder spear
#
public static void main(String[] args) throws Exception {
    System.out.print(Files.readString(Path.get("...")));
}
fallen larkBOT
sage bobcat
#

and make that "while" on the main?

#

@cinder spear

cinder spear
cinder spear
thick pier
#

it stores the whole file into one String

sage bobcat
#

so only this? @cinder spear

cinder spear
sage bobcat
thick pier
#

where is your File_Name.txt located?

sage bobcat
thick pier
#

then you need to give it the correct path

sage bobcat
thick pier
#

also use Path.of instead

thick pier
#

its probably something like C:\Users\name\Desktop\File_Name.txt or something like that

#

thats a path

#

in order to know where the file is located

#

normally your files are located in your resources folder though

sage bobcat
#

ye im getting what u saying but the Path.of where do i have to put it

#

btw the Paths.get and the "file name"?

sage bobcat
thick pier
#

use Path.of method instead of Paths.get

#

though it doesnt really matter

#

but iirc Paths.get is deprecated

sage bobcat
#

@thick pier still with errors

thick pier
#

because your Path is still wrong

sage bobcat
#

what is

#

I'm self-taught so most things idk

thick pier
#

its basically the location of your file

#

where C: is the identifier for a drive/partition

sage bobcat
#

ohh you mean the percors of the file

thick pier
#

and \ separates folders and files

sage bobcat
#

ye mb not familiare with those terms, now it worked i also added another "" to let it works

thick pier
#

and what is the location of your file

sage bobcat
#

desktop

thick pier
#

yeah but the full path/location

sage bobcat
#

can i run a .bat with this command i did?

thick pier
#

with the file reading?

sage bobcat
#

C:\Users\Desktop

#

there another but i cut

sage bobcat
thick pier
sage bobcat
#

why u want the name ?

thick pier
# sage bobcat C:\Users\\Desktop

then the full path is probably C:\Users\NAME\Desktop\File_Name.txt
and you would do it like this in your code:

Path.of("C:\Users\NAME\Desktop\File_Name.txt")
sage bobcat
#

i mean now i can to the same thing i did using Paths.get

thick pier
sage bobcat
thick pier
#

it wont work like you think

sage bobcat
#

its possible to run a .bat in the java program

thick pier
#

it would just read the content

#

but not run it

sage bobcat
#

alr

sage bobcat
#

thanks for helpin me, will i can ask again for help?

#

of this type

thick pier
#

yeah always

sage bobcat
#

stack overflow, ai, books or what else

thick pier
#

mooc.fi course and learning by doing, baeldung for specific topics, googling

fallen larkBOT
#

MOOC is a completely free introductory Java course created by the University of Helsinki, it is a great way to learn Java from the ground up.

It consists of two parts, one at beginner, and another at intermediate level. The end of the course is marked by creating your own Asteroids game clone!

Even though the instructions show how to configure and use NetBeans for the course, you can use IntelliJ. To use IntelliJ, simply install the TMC plugin by opening IntelliJ -> File -> Settings -> Plugins and searching for TMC. You will then be able to use IntelliJ to complete MOOC.

Visit MOOC here: https://java-programming.mooc.fi/
(the course is available in both English and Finnish)

About the course - Java Programming

sage bobcat
#

okok, now last question i swear

thick pier
#

all good

#

just ask

sage bobcat
thick pier
#

```

```

#

you can additionally include color formatting:
```java
System.out.println();
```

#

which ends up looking like:

System.out.println();
#

and for java it can recognize stuff like primitive types etc:

int variable = 0;
sage bobcat
#

alr will use

#

ty

fallen larkBOT
#

Closed the thread.

sage bobcat
#

@thick pier @vivid zephyr @cinder spear im going to try the corse of that mooc.fi, so which one do i have to choose, if i know arrays, i am good with matemathics and in general numbers problems with arrays, i know funcions too.
this all to embark on the world of Ethical Hckin. so idk which course do i have to choose

sage bobcat
thick pier
#

start at part 2

#

also you shouldnt ping helper for no reason