This site requires JavaScript, please enable it in your browser!
Greenfoot back
Darkstep
Darkstep wrote ...

2021/6/22

How to read and use a text file?

Darkstep Darkstep

2021/6/22

#
So what I want to be able to do is access a text file where I've written lines of addObjects that the world can use to add objects at those coordinates. I've seen some scanner methods but I don't know how to implement them and use them like I want to. Any code will help, thanks!
RcCookie RcCookie

2021/6/22

#
Disclaimer: this will not work online! How to read a (text) file Read the whole file into a string array:
import java.io.File;
import java.io.IOException;
import java.nio.Files;
import java.nio.Path;

// —-

File file = new File(„files/someFile.someSuffix“);
String[] lines;
try {
    lines = Files.readLines(Path.of(file)); // You can also pass the path string from above directly instead of the file object
} catch(IOException e) {
    System.err.println(„An exception occurred while reading the file “ + file);
}

// Example if you don’t know how to use arrays
String firstLine = lines[0];
int lineCount = lines.length;
Read a file character by character or line by line:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

// —-

File file = new File(…);
try {
    Scanner sc = new Scanner(file);
    while(sc.hasNext()) {
        char next = sc.next();
        // do something with it
    }
    
    // Alternatively
    while(sc.hasNext()) {
        String line = sc.nextLine();
        // …
    }
} catch // …
How to write text into a file
import java.io.File;
import java.io.IOException
import java.io.PrintWriter;

// —-

File file = new File(…);

// Create file and directories
new File(file.getParent()).mkDirs();
file.createNewFile();

// Write into file
try(PrintWriter writer = new PrintWriter(file)) {
    writer.printLn(„Hello World!“);
    // PrintWriter is similar to the default output stream „System.out“ / „System.err“, and has the same methods like print or printLn
} catch // …
RcCookie RcCookie

2021/6/22

#
Also you can name your File however you want, you may name it „.txt“, you may name it „.json“ or „.someWeirdSuffixThatDoesNotMakeSence“. The suffix is just a name and used by the OS to identify a program to use the file with. It has nothing to do with encoding. You can even leave the suffix away completely.
Darkstep Darkstep

2021/6/22

#
RcCookie wrote...
Disclaimer: this will not work online! How to read a (text) file Read the whole file into a string array:
import java.io.File;
import java.io.IOException;
import java.nio.Files;
import java.nio.Path;

// —-

File file = new File(„files/someFile.someSuffix“);
String[] lines;
try {
    lines = Files.readLines(Path.of(file)); // You can also pass the path string from above directly instead of the file object
} catch(IOException e) {
    System.err.println(„An exception occurred while reading the file “ + file);
}

// Example if you don’t know how to use arrays
String firstLine = lines[0];
int lineCount = lines.length;
Read a file character by character or line by line:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

// —-

File file = new File(…);
try {
    Scanner sc = new Scanner(file);
    while(sc.hasNext()) {
        char next = sc.next();
        // do something with it
    }
    
    // Alternatively
    while(sc.hasNext()) {
        String line = sc.nextLine();
        // …
    }
} catch // …
How to write text into a file
import java.io.File;
import java.io.IOException
import java.io.PrintWriter;

// —-

File file = new File(…);

// Create file and directories
new File(file.getParent()).mkDirs();
file.createNewFile();

// Write into file
try(PrintWriter writer = new PrintWriter(file)) {
    writer.printLn(„Hello World!“);
    // PrintWriter is similar to the default output stream „System.out“ / „System.err“, and has the same methods like print or printLn
} catch // …
Thanks but when I'm importing the stuff needed, it says for both Files and Path; cannot find symbol - class Files/Path
RcCookie RcCookie

2021/6/22

#
I’m sorry, it’s actually
java.nio.file.Files
You actually don’t need Path which is also in that package, just replace
Path.of(file)
with
file.toPath()
Darkstep Darkstep

2021/6/22

#
RcCookie wrote...
I’m sorry, it’s actually
java.nio.file.Files
You actually don’t need Path which is also in that package, just replace
Path.of(file)
with
file.toPath()
I've imported everything and changed the stuff but although that part's fixed now, for readLines it shows an error that says; cannot find symbol - method readLines(java.nio.file.Path). This is my code as of now:
import greenfoot.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class MyWorld extends World {
public void readFile() {        
        File file = new File("grid.txt");
        String[] lines;
        try {
            lines = Files.readLines(file.toPath()); 
        } catch(IOException e) {
            System.err.println("An exception occurred while reading the file " + file);
        }
    }
}
RcCookie RcCookie

2021/6/23

#
Sorry for the mistakes, I was just writing from what I remembered - aparently some wrong stuff. Here's how the reading actually works:
File file = // ...
List<String> lines;
try {
    lines = Files.readAllLines(file.toPath());
} catch // ...

// To convert list to array
String[] linesArray = lines.toArray(new String[0]);

// Or simply use the list directly
String firstLine = lines.get(0);
int linesCount = lines.size();

// Finally, you can also convert the list to a single string with newlines
import java.util.stream.Collectors;
// ---
String string = lines.stream().collect(Collectors.joining('\n');
Darkstep Darkstep

2021/6/23

#
RcCookie wrote...
Sorry for the mistakes, I was just writing from what I remembered - aparently some wrong stuff. Here's how the reading actually works:
File file = // ...
List<String> lines;
try {
    lines = Files.readAllLines(file.toPath());
} catch // ...

// To convert list to array
String[] linesArray = lines.toArray(new String[0]);

// Or simply use the list directly
String firstLine = lines.get(0);
int linesCount = lines.size();

// Finally, you can also convert the list to a single string with newlines
import java.util.stream.Collectors;
// ---
String string = lines.stream().collect(Collectors.joining('\n');
Nice, it works thanks! Sorry for more questions but for the writing in the text file portion it says for file.createNewFile(); unreported exception; must be caught or declared to be thrown.
RcCookie RcCookie

2021/6/23

#
Just put it into a try/catch block like the other times and catch an IOException. Orexpand the existing one:
try {
    file.createNewFile();
    PrintWriter writer = new PrintWriter(file);

    // Write something to the file

    // This was done automatically before because we used the „try-with-resources“ try/catch
    // before. Since the file first has to be created we would now have to close it ourself
    writer.close();
} catch(IOException e) {
    e.printStackTrace(); // Actually a better way of working with an exception
}
Also it’s fine, feel free to keep asking. Not the best explanation by me with all the mistakes.
You need to login to post a reply.