Update: Thanks for the quick responses, everyone. I've resolved the Charset issue, but now something else is happening that I don't understand at all. Here's my code:
import java.io.*;
import java.nio.file.*;
import java.nio.charset.*;
public class readConvertSeq{
private static String[] getFile(Path file){
String[] fileArray = (String[])Files.readAllLines(file, StandardCharsets.US_ASCII).toArray();
return fileArray;
}
public static void main(String[] args){
String[] test = readConvertSeq.getFile(Paths.get(args[0]));
int i;
for(i = 0; i < test.length; i++){
System.out.println(test[i]);
}
}
}
And here's the error:
readConvertSeq.java:6: error: unreported exception IOException; must be caught or declared to be thrown
String[] fileArray = (String[])Files.readAllLines(file, StandardCharsets.US_ASCII).toArray();
I'm just trying to get an array of strings from a file, and I'm getting really frustrated by Java's pedantry. Here's my code:
import java.io.*;
import java.nio.file.*;
import java.nio.charset.*;
public class readConvertSeq{
private static String[] getFile(Path file){
String[] fileArray = Files.readAllLines(file, Charset("US-ASCII")).toArray();
return fileArray;
}
public static void main(String[] args){
String[] test = readConvertSeq.getFile(Paths.get(args[0]));
int i;
for(i = 0; i < test.length; i++){
System.out.println(test[i]);
}
}
}
It gives me this:
readConvertSeq.java:6: error: cannot find symbol
String[] fileArray = Files.readAllLines(file, Charset("US-ASCII")).toArray();
^
symbol: method Charset(String)
location: class readConvertSeq
I'm sure I've made some other mistakes as well, so feel free to give me any advice you can.
Charset is an abstract class therefore you cannot instantiate it with the new keyword.
To get a charset in Java 1.7 use StandardCharsets.US_ASCII
Constructors in Java are called with the new
operator, so Charset("US-ASCII")
is not a valid statement.
Moreover, Charset
's constructor is protected, so you'll have to use the static factory method to create it: Charset.forName("US-ASCII")
.
You need to make the below changes
String[] fileArray = (String[]) Files.readAllLines(file.toPath(), Charset.forName("US-ASCII")).toArray();
^^^^^ - Cast required ^^^^ - Get Charset using forName
See the docs of Files.readAllLines(Path, Charset)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With