Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readAllLines Charset in Java

Tags:

java

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.

like image 385
blimpse Avatar asked Oct 19 '13 17:10

blimpse


3 Answers

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

like image 125
Mateusz Dymczyk Avatar answered Nov 07 '22 17:11

Mateusz Dymczyk


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").

like image 5
Mureinik Avatar answered Nov 07 '22 17:11

Mureinik


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).

like image 3
Rahul Avatar answered Nov 07 '22 15:11

Rahul