ReadAllLines Charset in Java

Update: thanks for the quick answers, that's it. I solved the Charset problem, but now something else is happening that I donโ€™t understand at all. Here is 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 is 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 really disappointed with Java pedantry. Here is 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]); } } } 

This gives me the following:

 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 made some other mistakes, so feel free to give me any advice.

+6
source share
4 answers

Charset is an abstract class, so you cannot create it using the new keyword.

To get the encoding in Java 1.7, use StandardCharsets.US_ASCII

+8
source

Constructors in Java are called using the new operator, so Charset("US-ASCII") not a valid operator. Moreover, the Charset constructor is protected, so to create it you need the static factory method: Charset.forName("US-ASCII") .

+5
source

You need to make the following changes

 String[] fileArray = (String[]) Files.readAllLines(file.toPath(), Charset.forName("US-ASCII")).toArray(); ^^^^^ - Cast required ^^^^ - Get Charset using forName 

See documents Files.readAllLines(Path, Charset) .

+3
source

Charset does not have a common constructor, so you need to use the static factory method Charset # forName

+2
source

Source: https://habr.com/ru/post/956323/


All Articles