1

我在 java 中使用了一些配置文件和文件阅读器类。我总是用数组读/写文件,因为我正在处理对象。这看起来有点像这样:

public void loadUserData(ArrayList<User> arraylist) {
    try {
        List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
        for(String line : lines) {
            String[] userParams = line.split(";");

            String name = userParams[0];
            String number= userParams[1];
            String mail = userParams[2];

            arraylist.add(new User(name, number, mail));
        }   
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这很好用,但是如何将文件的内容保存为一个字符串?

当我读取文件时,我使用的字符串应该与文件的内容完全相同(不使用数组或行拆分)。我怎样才能做到这一点?

编辑:

我尝试从文件中读取 SQL 语句,以便稍后将其与 JDBC 一起使用。这就是为什么我需要文件的内容作为单个字符串

4

4 回答 4

2

这种方法会奏效

public static void readFromFile() throws Exception{
        FileReader fIn = new FileReader("D:\\Test.txt");
        BufferedReader br = new BufferedReader(fIn);
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        String text = sb.toString();
        System.out.println(text);

}
于 2013-06-24T10:14:07.060 回答
1

只需这样做:

final FileChannel fc;
final String theFullStuff;

try (
    fc = FileChannel.open(path, StandardOpenOptions.READ);
) {
    final ByteBuffer buf = ByteBuffer.allocate(fc.size());
    fc.read(buf);
    theFullStuff = new String(buf.array(), theCharset);
}

蔚来赢了!:p

于 2013-06-24T09:57:24.543 回答
1

你总是可以创建一个缓冲阅读器,例如

File anInputFile = new File(/*input path*/);
FileReader aFileReader = new FileReader(anInputFile);
BufferedReader reader = new BufferedReader(aFileReader)

String yourSingleString = "";
String aLine = reader.readLine();

while(aLine != null)
{
    singleString += aLine + " ";
    aLine = reader.readLine();
}
于 2013-06-24T09:58:43.893 回答
1

我希望这是你需要的:

public void loadUserData(ArrayList<User> arraylist) {
    StringBuilder sb = new StringBuilder();
    try {
        List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
        for(String line : lines) {
           // String[] userParams = line.split(";");

            //String name = userParams[0];
            //String number= userParams[1];
            //String mail = userParams[2];
            sb.append(line);
        }   
        String jdbcString = sb.toString();
        System.out.println("JDBC statements read from file: " + jdbcString );
    } catch (IOException e) {
        e.printStackTrace();
    }
}

或者这个:

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);
于 2013-06-24T09:50:19.173 回答