Example usage for java.io InputStreamReader getEncoding

List of usage examples for java.io InputStreamReader getEncoding

Introduction

In this page you can find the example usage for java.io InputStreamReader getEncoding.

Prototype

public String getEncoding() 

Source Link

Document

Returns the name of the character encoding being used by this stream.

Usage

From source file:Main.java

public static void main(String[] args) throws IOException {
    // new input stream reader is created
    FileInputStream fis = new FileInputStream("C:/test.txt");
    InputStreamReader isr = new InputStreamReader(fis);

    // the name of the character encoding returned
    String s = isr.getEncoding();
    System.out.print("Character Encoding: " + s);
    isr.close();//from  w  ww .j  ava  2s  . com
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.io.InFile.java

public static String readFileText(String file, String encoding) throws IOException {
     File f = new File(file);
     InputStreamReader isr = new InputStreamReader(new FileInputStream(f), encoding);
     System.out.println("character encoding = " + isr.getEncoding());
     int c;/*from ww w .ja v  a2s .  c  o  m*/
     StringBuffer res = new StringBuffer();
     while ((c = isr.read()) != -1) {
         res.append((char) c);
     }
     isr.close();
     return res.toString();
 }

From source file:ar.com.tadp.xml.rinzo.core.utils.FileUtils.java

/**
 * Guarda un documento localmente en la cache
 *//*from w w  w  .  j  av a2  s. c om*/
public static void saveFile(String inputFileName, File outputFile) {
    InputStream openStream = null;
    BufferedReader reader = null;
    BufferedWriter writer = null;
    try {
        File inputFile = new File(inputFileName);
        if (!inputFile.exists()) {
            openStream = new URL(inputFileName).openStream();
            InputStreamReader is = new InputStreamReader(openStream);
            String encoding = is.getEncoding();
            reader = new BufferedReader(is);
            writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(outputFile, false), encoding));

            String line = reader.readLine();
            while (line != null) {
                writer.write(line);
                writer.newLine();
                writer.flush();
                line = reader.readLine();
            }
        }
    } catch (Exception exception) {
        throw new RuntimeException("Error trying to save \'" + inputFileName + "\' in the cache.", exception);
    } finally {
        try {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (openStream != null) {
                openStream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(
                    "Error trying to close files while saving \'" + inputFileName + "\' in the cache.", e);
        }
    }
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java

public static String getDefaultCharEncoding() {
    byte[] bArray = { 'w' };
    InputStream is = new ByteArrayInputStream(bArray);
    InputStreamReader reader = new InputStreamReader(is);
    String defaultCharacterEncoding = reader.getEncoding();
    return defaultCharacterEncoding;
}

From source file:com.xxg.jdeploy.util.FileUtil.java

/**
 * /*w  w w  .  ja  v a 2s  .c  om*/
 * @param fileName
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
public static String getFileEncoding(String fileName) throws IOException {
    InputStreamReader read = null;
    String encoding = "";
    try {
        read = new InputStreamReader(new FileInputStream(new File(fileName)));
        encoding = read.getEncoding();
        read.close();
    } catch (IOException e) {
        throw e;
    } finally {
        if (read != null) {
            try {
                read.close();
            } catch (IOException e) {
                throw e;
            }
        }
    }
    return encoding;
}

From source file:org.tinymediamanager.TinyMediaManager.java

/**
 * debug various JVM character settings/*from ww w. j ava  2  s.  co m*/
 */
private static void debugCharacterEncoding(String text) {
    String defaultCharacterEncoding = System.getProperty("file.encoding");
    byte[] bArray = { 'w' };
    InputStream is = new ByteArrayInputStream(bArray);
    InputStreamReader reader = new InputStreamReader(is);
    LOGGER.info(
            text + defaultCharacterEncoding + " | " + reader.getEncoding() + " | " + Charset.defaultCharset());
}

From source file:org.pentaho.di.trans.steps.fileinput.text.TextFileInputUtils.java

public static final String getLine(LogChannelInterface log, InputStreamReader reader, int formatNr,
        StringBuilder line) throws KettleFileException {
    EncodingType type = EncodingType.guessEncodingType(reader.getEncoding());
    return getLine(log, reader, type, formatNr, line);
}

From source file:org.obm.push.mail.bean.EmailReader.java

public EmailReader(InputStreamReader inputStreamReader) {
    this(inputStreamReader, Charset.forName(inputStreamReader.getEncoding()));
}

From source file:com.evolveum.midpoint.tools.ninja.ImportObjects.java

public boolean execute() {
    System.out.println("Starting objects import.");

    File objects = new File(filePath);
    if (!objects.exists() || !objects.canRead()) {
        System.out.println(/*  ww  w .j  a  v a2 s. c om*/
                "XML file with objects '" + objects.getAbsolutePath() + "' doesn't exist or can't be read.");
        return false;
    }

    InputStream input = null;
    ClassPathXmlApplicationContext context = null;
    try {
        System.out.println("Loading spring contexts.");
        context = new ClassPathXmlApplicationContext(CONTEXTS);

        InputStreamReader reader = new InputStreamReader(new FileInputStream(objects), "utf-8");
        input = new ReaderInputStream(reader, reader.getEncoding());

        final RepositoryService repository = context.getBean("repositoryService", RepositoryService.class);
        PrismContext prismContext = context.getBean(PrismContext.class);

        EventHandler handler = new EventHandler() {

            @Override
            public EventResult preMarshall(Element objectElement, Node postValidationTree,
                    OperationResult objectResult) {
                return EventResult.cont();
            }

            @Override
            public <T extends Objectable> EventResult postMarshall(PrismObject<T> object, Element objectElement,
                    OperationResult objectResult) {
                try {
                    String displayName = getDisplayName(object);
                    System.out.println("Importing object " + displayName);

                    repository.addObject((PrismObject<ObjectType>) object, null, objectResult);
                } catch (Exception ex) {
                    objectResult.recordFatalError("Unexpected problem: " + ex.getMessage(), ex);

                    System.out.println("Exception occurred during import, reason: " + ex.getMessage());
                    ex.printStackTrace();
                }

                objectResult.recordSuccessIfUnknown();
                if (objectResult.isAcceptable()) {
                    // Continue import
                    return EventResult.cont();
                } else {
                    return EventResult.skipObject(objectResult.getMessage());
                }
            }

            @Override
            public void handleGlobalError(OperationResult currentResult) {
            }
        };
        Validator validator = new Validator(prismContext, handler);
        validator.setVerbose(true);
        validator.setValidateSchema(validateSchema);

        OperationResult result = new OperationResult("Import objeccts");
        validator.validate(input, result, OperationConstants.IMPORT_OBJECT);

        result.recomputeStatus();
        if (!result.isSuccess()) {
            System.out.println("Operation result was not success, dumping result.\n" + result.debugDump(3));
        }
    } catch (Exception ex) {
        System.out.println("Exception occurred during import task, reason: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        destroyContext(context);
    }

    System.out.println("Objects import finished.");
    return true;
}

From source file:com.evolveum.midpoint.web.page.admin.configuration.PageImportObject.java

private void saveFilePerformed(AjaxRequestTarget target) {
    OperationResult result = new OperationResult(OPERATION_IMPORT_FILE);

    FileUploadField file = (FileUploadField) get(
            createComponentPath(ID_MAIN_FORM, ID_INPUT, ID_INPUT_FILE, ID_FILE_INPUT));
    final FileUpload uploadedFile = file.getFileUpload();
    if (uploadedFile == null) {
        error(getString("pageImportObject.message.nullFile"));
        target.add(getFeedbackPanel());/*from  w w w .  ja  v  a2 s . co  m*/

        return;
    }

    InputStream stream = null;
    File newFile = null;
    try {
        // Create new file
        MidPointApplication application = getMidpointApplication();
        WebApplicationConfiguration config = application.getWebApplicationConfiguration();
        File folder = new File(config.getImportFolder());
        if (!folder.exists() || !folder.isDirectory()) {
            folder.mkdir();
        }

        newFile = new File(folder, uploadedFile.getClientFileName());
        // Check new file, delete if it already exists
        if (newFile.exists()) {
            newFile.delete();
        }
        // Save file
        Task task = createSimpleTask(OPERATION_IMPORT_FILE);
        newFile.createNewFile();
        uploadedFile.writeTo(newFile);

        InputStreamReader reader = new InputStreamReader(new FileInputStream(newFile), "utf-8");
        stream = new ReaderInputStream(reader, reader.getEncoding());
        getModelService().importObjectsFromStream(stream, model.getObject(), task, result);

        result.recomputeStatus();
    } catch (Exception ex) {
        result.recordFatalError("Couldn't import file.", ex);
        LoggingUtils.logException(LOGGER, "Couldn't import file", ex);
    } finally {
        if (stream != null) {
            IOUtils.closeQuietly(stream);
        }
        if (newFile != null) {
            FileUtils.deleteQuietly(newFile);
        }
    }

    showResult(result);
    target.add(getFeedbackPanel());
}