-5

可能重复:
如何从文件内容创建 Java 字符串

我正在制作一个 java 程序来读取文件并创建有趣的文件。我想知道如何从文件中读取并将其设置为字符串变量。或者将扫描仪变量转换为字符串变量,这里以编码的一部分为例:

    private Scanner x;
    private JLabel label;
    private String str;

    public void openfile(String st){


        try{
            x = new Scanner(new File(st));
        }
        catch(Exception e){
            System.out.println("Error: File Not Found");
        }
    }
4

5 回答 5

1

这是一个强大的oneliner。

String contents = new Scanner(file).useDelimiter("\\Z").next(); 
于 2012-06-03T19:17:42.900 回答
1

这样做的好方法是使用 Apache commons IOUtils 将 inputStream 复制到 StringWriter 中......类似于

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

或者,如果您不想混合使用 Streams 和 Writers,则可以使用 ByteArrayOutputStream

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream,%20java.lang.String%29

于 2012-06-03T19:20:42.217 回答
0

或者你甚至可以试试这个:

 ArrayList <String> theWord = new ArrayList <String>();
            //while it has next ..
            while(x.hasNext()){
                //Initialise str with word read
                String str=x.next();
                //add to ArrayList
                theWord.add(str);

            }
            //print the ArrayList
            System.out.println(theWord);

        }
于 2012-06-03T19:20:26.420 回答
0

这是一个如何将文件读入字符串的示例:

public String readDocument(File document)
        throws SystemException {
    InputStream is = null;
    try {
        is = new FileInputStream(document);
        long length = document.length();
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        if (offset < bytes.length) {
            throw new SystemException("Could not completely read file: " + document.getName());
        }
        return new String(bytes);
    } catch (FileNotFoundException e) {
        LOGGER.error("File not found exception occurred", e);
        throw new SystemException("File not found exception occurred.", e);
    } catch (IOException e) {
        LOGGER.error("IO exception occurred while reading file.", e);
        throw new SystemException("IO exception occurred while reading file.", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                LOGGER.error("IO exception occurred while closing stream.", e);
            }
        }
    }
}
于 2012-06-03T19:20:59.237 回答
0
BufferedReader in =new BufferedReader(new FileReader(filename));
    String strLine;
    while((strLine=in.readLine())!=null){
    //do whatever you want with that string here
    }
于 2012-06-03T19:25:20.333 回答