String zerlegen

Hallo,

das kann man auf mehrere Arten machen, hier mal zwei Beispiele:
Java:
/**
 * 
 */
package de.tutorials;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Scanner;

/**
 * @author thomas.darimont
 * 
 */
public class GetTextFileContentAsStringExample {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(new File("d:/UserTablespaces.sql"));
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        while (scanner.hasNextLine()) {
            printWriter.println(scanner.nextLine());
        }
        scanner.close();
        printWriter.close();
        
        String contents = stringWriter.toString();
        
        System.out.println(contents);
    }
}

oder so:
Java:
/**
 * 
 */
package de.tutorials;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.channels.Channels;

/**
 * @author thomas.darimont
 * 
 */
public class GetTextFileContentAsStringExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		File file = new File("d:/UserTablespaces.sql");
		FileInputStream fileInputStream = new FileInputStream(file);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		fileInputStream.getChannel().transferTo(0, (int) file.length(),
				Channels.newChannel(byteArrayOutputStream));
		System.out.println(new String(byteArrayOutputStream.toByteArray(),
				"UTF-8")); //entsprechendes Encoding setzen...
	}
}

Gruß Tom
 
Zurück