7

更新:感谢大家的快速回复。我已经解决了 Charset 问题,但现在发生了一些我完全不明白的事情。这是我的代码:

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]);
        }   
    }   
}  

这是错误:

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();

我只是想从一个文件中获取一个字符串数组,而我对 Java 的迂腐感到非常沮丧。这是我的代码:

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]);
        }   
    }   
}   

它给了我这个:

readConvertSeq.java:6: error: cannot find symbol
    String[] fileArray = Files.readAllLines(file, Charset("US-ASCII")).toArray();
                                                  ^
  symbol:   method Charset(String)
  location: class readConvertSeq

我敢肯定我也犯了其他一些错误,所以请随时给我任何建议。

4

4 回答 4

10

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

于 2013-10-19T17:32:46.417 回答
5

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

于 2013-10-19T17:32:58.717 回答
3

您需要进行以下更改

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

请参阅 的文档Files.readAllLines(Path, Charset)

于 2013-10-19T17:32:06.590 回答
2

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

于 2013-10-19T17:33:23.453 回答