-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

これが強力なワンライナーです。

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

または、ストリームとライターを混在させたくない場合は、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 に答える