Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

In this page you can find the example usage for java.io OutputStreamWriter write.

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.marginallyclever.makelangelo.MainGUI.java

protected boolean LoadDXF(String filename) {
    if (ChooseImageConversionOptions(true) == false)
        return false;

    // where to save temp output file?
    final String destinationFile = GetTempDestinationFile();
    final String srcFile = filename;

    TabToLog();/*from   www.  j av  a  2 s  . c om*/

    final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100);
    pm.setProgress(0);
    pm.setMillisToPopup(0);

    final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() {
        public boolean ok = false;

        @SuppressWarnings("unchecked")
        @Override
        public Void doInBackground() {
            Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n");

            Parser parser = ParserBuilder.createDefaultParser();

            double dxf_x2 = 0;
            double dxf_y2 = 0;
            OutputStreamWriter out = null;

            try {
                out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8");
                DrawingTool tool = machineConfiguration.GetCurrentTool();
                out.write(machineConfiguration.GetConfigLine() + ";\n");
                out.write(machineConfiguration.GetBobbinLine() + ";\n");
                out.write("G00 G90;\n");
                tool.WriteChangeTo(out);
                tool.WriteOff(out);

                parser.parse(srcFile, DXFParser.DEFAULT_ENCODING);
                DXFDocument doc = parser.getDocument();
                Bounds b = doc.getBounds();
                double width = b.getMaximumX() - b.getMinimumX();
                double height = b.getMaximumY() - b.getMinimumY();
                double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f;
                double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f;
                double sy = machineConfiguration.GetPaperHeight() * 10 / height;
                double sx = machineConfiguration.GetPaperWidth() * 10 / width;
                double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin;
                sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1);
                // count all entities in all layers
                Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator();
                int entity_total = 0;
                int entity_count = 0;
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();
                    Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n");
                    Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_iter.hasNext()) {
                        String entity_type = (String) entity_iter.next();
                        List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type);
                        Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type
                                + "</font>\n");
                        entity_total += entity_list.size();
                    }
                }
                // set the progress meter
                pm.setMinimum(0);
                pm.setMaximum(entity_total);

                // convert each entity
                layer_iter = doc.getDXFLayerIterator();
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();

                    Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_type_iter.hasNext()) {
                        String entity_type = (String) entity_type_iter.next();
                        List<DXFEntity> entity_list = layer.getDXFEntities(entity_type);

                        if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFLine entity = (DXFLine) entity_list.get(i);
                                Point start = entity.getStartPoint();
                                Point end = entity.getEndPoint();

                                double x = (start.getX() - cx) * sx;
                                double y = (start.getY() - cy) * sy;
                                double x2 = (end.getX() - cx) * sx;
                                double y2 = (end.getY() - cy) * sy;

                                // is it worth drawing this line?
                                double dx = x2 - x;
                                double dy = y2 - y;
                                if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) {
                                    continue;
                                }

                                dx = dxf_x2 - x;
                                dy = dxf_y2 - y;

                                if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                    if (tool.DrawIsOn()) {
                                        tool.WriteOff(out);
                                    }
                                    tool.WriteMoveTo(out, (float) x, (float) y);
                                }
                                if (tool.DrawIsOff()) {
                                    tool.WriteOn(out);
                                }
                                tool.WriteMoveTo(out, (float) x2, (float) y2);
                                dxf_x2 = x2;
                                dxf_y2 = y2;
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFSpline entity = (DXFSpline) entity_list.get(i);
                                entity.setLineWeight(30);
                                DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity);
                                boolean first = true;
                                for (int j = 0; j < polyLine.getVertexCount(); ++j) {
                                    DXFVertex v = polyLine.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < polyLine.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFPolyline entity = (DXFPolyline) entity_list.get(i);
                                boolean first = true;
                                for (int j = 0; j < entity.getVertexCount(); ++j) {
                                    DXFVertex v = entity.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < entity.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        }
                    }
                }

                // entities finished.  Close up file.
                tool.WriteOff(out);
                tool.WriteMoveTo(out, 0, 0);

                ok = true;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            pm.setProgress(100);
            return null;
        }

        @Override
        public void done() {
            pm.close();
            Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
            PlayConversionFinishedSound();
            if (ok) {
                LoadGCode(destinationFile);
                TabToDraw();
            }
            Halt();
        }
    };

    s.addPropertyChangeListener(new PropertyChangeListener() {
        // Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                pm.setProgress(progress);
                String message = String.format("%d%%\n", progress);
                pm.setNote(message);
                if (s.isDone()) {
                    Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
                } else if (s.isCancelled() || pm.isCanceled()) {
                    if (pm.isCanceled()) {
                        s.cancel(true);
                    }
                    Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n");
                }
            }
        }
    });

    s.execute();

    return true;
}

From source file:com.athena.chameleon.engine.threadpool.task.FileEncodingConvertTask.java

@Override
protected void taskRun() {
    OutputStreamWriter output = null;
    InputStream input = null;/*  w  w  w.  j a  v a 2  s. com*/

    try {
        input = new FileInputStream(file);
        byte[] data = IOUtils.toByteArray(input, file.length());
        IOUtils.closeQuietly(input);

        /*
         * CharsetDector ? ? ?? ?.
         * 
         * UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE, Shift_JIS, ISO-2022-JP, 
         * ISO-2022-CN, ISO-2022-KR, GB18030, EUC-JP, EUC-KR, Big5, ISO-8859-1, 
         * ISO-8859-2, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, windows-1251, 
         * windows-1256, KOI8-R, ISO-8859-9, IBM424_rtl, IBM424_ltr, IBM420_rtl, IBM420_ltr
         */
        // ? ? defaultEncoding    ? 
        // new CharsetDetector().getString(data, defaultEncoding);  ?? ? ? ? 
        // ?? null  ?? ?.
        //String fileContents = new CharsetDetector().getString(data, defaultEncoding);

        String fileContents = null;
        com.ibm.icu.text.CharsetMatch cm = null;

        try {
            CharsetDetector detector = new CharsetDetector();
            detector.setDeclaredEncoding(defaultEncoding);
            detector.setText(data);
            cm = detector.detect();

            fileContents = cm.getString();

            //logger.debug("Encoding => {}" + cm.getName());
            //logger.debug("Contents => {}" + cm.getString());
        } catch (Exception e) {
            // Ignore...
        }

        if (fileContents != null) {
            // html, jsp, xml ?? ? Character Set  ?? ???  UTF-8 
            // charset=EUC-KR, encoding="EUC-KR"    EUC-KR, ISO-8859-1  
            //    SEARCH_CHAR_SET? 
            if (ArrayUtils.contains(TARGET_SUFFIX, extension)) {
                fileContents = replace(fileContents);
            }

            output = new OutputStreamWriter(new FileOutputStream(file), defaultEncoding);
            output.write(fileContents);
            IOUtils.closeQuietly(output);
        }
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException has occurred : ", e);
    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException has occurred : ", e);
    } catch (IOException e) {
        logger.error("IOException has occurred : ", e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:au.org.ala.names.search.ALANameSearcher.java

/**
 * Dumps a list of the species LSID's that are contained in the index.
 *///  www  .  j  av a2s  .c  om
public void dumpSpecies() {
    try {
        OutputStreamWriter fileOut = new OutputStreamWriter(new FileOutputStream("/data/species.txt"), "UTF-8");
        Term term = new Term("rank", "species");
        TopDocs hits = cbSearcher.search(new TermQuery(term), 2000000);

        for (ScoreDoc sdoc : hits.scoreDocs) {
            Document doc = cbReader.document(sdoc.doc);

            if (doc.getField("synonym") == null) {
                String lsid = StringUtils.trimToNull(doc.getField("lsid").stringValue());
                if (lsid == null)
                    lsid = doc.getField("id").stringValue();
                fileOut.write(lsid + "\n");
            }

        }
        fileOut.flush();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * Write a String to a text file using given encoding
 * @param sFilePath Full file path. For example "file:///tmp/myfile.txt" or "ftp://localhost:21/tmp/myfile.txt"
 * @param sText String to be written//from  ww w  . j  av  a 2 s.c om
 * @param sEncoding Encoding to be used
 * see <a href="http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html">Java Supported Encodings</a>
 * @throws IOException
 * @throws OutOfMemoryError
 */
public void writefilestr(String sFilePath, String sText, String sEncoding)
        throws IOException, OutOfMemoryError {

    if (DebugFile.trace) {
        DebugFile.writeln("Begin FileSystem.writefilestr(" + sFilePath + ", ..., " + sEncoding + ")");
        DebugFile.incIdent();
    }

    String sLower = sFilePath.toLowerCase();

    if (sLower.startsWith("file://"))
        sFilePath = sFilePath.substring(7);

    if (sLower.startsWith("ftp://")) {

        FTPClient oFTPC = null;
        boolean bFTPSession = false;

        splitURI(sFilePath);

        try {

            if (DebugFile.trace)
                DebugFile.writeln("new FTPClient(" + sHost + ")");
            oFTPC = new FTPClient(sHost);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
            oFTPC.login(sUsr, sPwd);

            bFTPSession = true;

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
            oFTPC.chdir(sPath);

            oFTPC.setType(FTPTransferType.BINARY);
            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.put(byte[], " + sFile + ")");
            oFTPC.put(sText.getBytes(sEncoding), sFile);
        } catch (FTPException ftpe) {
            throw new IOException(ftpe.getMessage());
        } finally {
            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.quit()");
            try {
                if (bFTPSession)
                    oFTPC.quit();
            } catch (Exception ignore) {
            }
        }
    } else {
        FileOutputStream oOutStrm = new FileOutputStream(sFilePath);

        if (sText.length() > 0) {
            BufferedOutputStream oBFStrm = new BufferedOutputStream(oOutStrm, sText.length());
            OutputStreamWriter oWriter = new OutputStreamWriter(oBFStrm, sEncoding);
            oWriter.write(sText);
            oWriter.close();
            oBFStrm.close();
        } // fi (sText!="")

        oOutStrm.close();
    }
    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.writefilestr()");
    }
}

From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java

public void testDoImportUsersFromFileNoToken()
        throws AccessDeniedException, UserNotSignedException, IOException {
    AdminUserJspBean bean = new AdminUserJspBean();
    MockHttpServletRequest request = new MockHttpServletRequest();
    AdminUser user = getUserToModify();/*from w  w w. j ava 2  s.  c o m*/
    AdminAuthenticationService.getInstance().registerUser(request, user);
    bean.init(request, "CORE_USERS_MANAGEMENT");
    Map<String, List<FileItem>> multipartFiles = new HashMap<>();
    List<FileItem> fileItems = new ArrayList<>();
    FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024,
            new File(System.getProperty("java.io.tmpdir")));
    OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8"));
    writer.write(
            "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;");
    writer.close();
    fileItems.add(file);
    multipartFiles.put("import_file", fileItems);
    Map<String, String[]> parameters = request.getParameterMap();
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles,
            parameters);
    bean.getImportUsersFromFile(request); // initialize _importAdminUserService
    AdminUser importedUser = null;
    try {
        bean.doImportUsersFromFile(multipartRequest);
        fail("Should have thrown");
    } catch (AccessDeniedException e) {
        importedUser = AdminUserHome.findUserByLogin("test");
        assertNull(importedUser);
    } finally {
        if (importedUser != null) {
            disposeOfUser(importedUser);
        }
        disposeOfUser(user);
    }
}

From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java

public void testDoImportUsersFromFileInvalidToken()
        throws AccessDeniedException, UserNotSignedException, IOException {
    AdminUserJspBean bean = new AdminUserJspBean();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance().getToken(request, "jsp/admin/user/ImportUser.jsp") + "b");
    AdminUser user = getUserToModify();//  w w w .ja  v a  2 s  .co m
    AdminAuthenticationService.getInstance().registerUser(request, user);
    bean.init(request, "CORE_USERS_MANAGEMENT");
    Map<String, List<FileItem>> multipartFiles = new HashMap<>();
    List<FileItem> fileItems = new ArrayList<>();
    FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024,
            new File(System.getProperty("java.io.tmpdir")));
    OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8"));
    writer.write(
            "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;");
    writer.close();
    fileItems.add(file);
    multipartFiles.put("import_file", fileItems);
    Map<String, String[]> parameters = request.getParameterMap();
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles,
            parameters);
    bean.getImportUsersFromFile(request); // initialize _importAdminUserService
    AdminUser importedUser = null;
    try {
        bean.doImportUsersFromFile(multipartRequest);
        fail("Should have thrown");
    } catch (AccessDeniedException e) {
        importedUser = AdminUserHome.findUserByLogin("test");
        assertNull(importedUser);
    } finally {
        if (importedUser != null) {
            disposeOfUser(importedUser);
        }
        disposeOfUser(user);
    }
}

From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java

public void testDoImportUsersFromFile() throws AccessDeniedException, UserNotSignedException, IOException {
    AdminUserJspBean bean = new AdminUserJspBean();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance().getToken(request, "jsp/admin/user/ImportUser.jsp"));
    AdminUser user = getUserToModify();/*  www  .  j av a  2s.c o m*/
    AdminAuthenticationService.getInstance().registerUser(request, user);
    bean.init(request, "CORE_USERS_MANAGEMENT");
    Map<String, List<FileItem>> multipartFiles = new HashMap<>();
    List<FileItem> fileItems = new ArrayList<>();
    FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024,
            new File(System.getProperty("java.io.tmpdir")));
    OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8"));
    writer.write(
            "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;");
    writer.close();
    fileItems.add(file);
    multipartFiles.put("import_file", fileItems);
    Map<String, String[]> parameters = request.getParameterMap();
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles,
            parameters);
    bean.getImportUsersFromFile(request); // initialize _importAdminUserService
    AdminUser importedUser = null;
    try {
        bean.doImportUsersFromFile(multipartRequest);
        importedUser = AdminUserHome.findUserByLogin("test");
        assertNotNull(importedUser);
        assertEquals("test", importedUser.getAccessCode());
        assertEquals("test", importedUser.getFirstName());
        assertEquals("test", importedUser.getLastName());
        assertEquals("test@test.fr", importedUser.getEmail());
        assertEquals(AdminUser.ACTIVE_CODE, importedUser.getStatus());
    } finally {
        if (importedUser != null) {
            disposeOfUser(importedUser);
        }
        disposeOfUser(user);
    }
}

From source file:org.smilec.smile.student.CourseList.java

private void logError(String url, String err) {
    boolean reachable = false;
    String internetTest = "";
    String str = "";
    Date now = new Date();

    internetTest = now.toString() + ", loading page " + url + " error: " + err + "\n";
    ;/*w w  w .  ja v  a 2s.  c  om*/
    System.out.println(internetTest);

    try {
        //test router
        //InetAddress address = InetAddress.getByName("192.168.2.1");
        byte[] b = new byte[] { (byte) 192, (byte) 168, (byte) 2, (byte) 1 };
        InetAddress address = InetAddress.getByAddress(b);

        // Try to reach the specified address within the timeout
        // periode. If during this periode the address cannot be
        // reach then the method returns false.
        reachable = address.isReachable(5000); // 5 seconds            
    } catch (Exception e) {
        reachable = false;
        e.printStackTrace();
    }

    str = "Is router (192.168.2.1) reachable? " + reachable + "\n";
    System.out.println(str);
    internetTest += str;

    try {
        //test server
        InetAddress address = InetAddress.getByName(cururi);
        reachable = address.isReachable(5000);

    } catch (Exception e) {
        reachable = false;
        e.printStackTrace();
    }

    str = "Is host reachable? " + reachable + "\n";
    System.out.println(str);
    internetTest += str;
    String received = "";
    int statusCode = 0;

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 5000); // until first connection
        HttpConnectionParams.setSoTimeout(params, 5000); // 10000 ms socket timeout --? no time out for socket
        HttpClient httpclient = new DefaultHttpClient(params);
        HttpGet httpget;
        httpget = new HttpGet("http://" + cururi);
        HttpResponse response = httpclient.execute(httpget);
        statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 404) {
            // server not ready
            // do nothing                           
            throw new Exception("" + response.getStatusLine());
        } else if ((statusCode / 100) != 2) {
            throw new Exception("" + response.getStatusLine());
        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line;
            StringBuffer sb = new StringBuffer("");
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }

            received = sb.toString();

            if (received != null && received.length() > 0)
                reachable = true;

            received = "http status code: " + statusCode;
        }

    } catch (Exception e) {
        //e.printStackTrace();
        received = "loading error, http status code: " + statusCode;
        reachable = false;
    }

    str = "Is Apache reachable? " + reachable + ", " + received + "\n";
    System.out.println(str);
    internetTest += str;

    try {
        // open myfilename.txt for writing
        Log.d("Write log Err", "Start writing error log");
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput("smileErrorLog.txt", 0));
        out.write(internetTest);
        out.close();
        Log.d("Write log Err", "Writing error log finished.");
    } catch (java.io.IOException e) {
        //do something if an IOException occurs.
        Log.d("Write log Error", "ERROR");
        e.printStackTrace();
    }

}

From source file:edu.gslis.ts.ThriftToTREC.java

/**
 * @param thriftFile/*from  w w  w  .  j  a v  a2  s .co m*/
 */
public Map<String, String> filter(File infile, File outfile, String parser) {
    Map<String, String> results = new TreeMap<String, String>();
    try {
        InputStream in = null;

        if (infile.getName().endsWith(".gz"))
            in = new GZIPInputStream(new FileInputStream(infile));
        else if (infile.getName().endsWith("xz"))
            in = new XZInputStream(new FileInputStream(infile));
        else
            in = new FileInputStream(infile);

        TTransport inTransport = new TIOStreamTransport(new BufferedInputStream(in));
        TBinaryProtocol inProtocol = new TBinaryProtocol(inTransport);
        inTransport.open();

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outfile, false), "UTF-8");
        try {
            Charset charset = Charset.forName("UTF-8");
            CharsetDecoder decoder = charset.newDecoder();

            // Run through items in the thrift file
            while (true) {
                final StreamItem item = new StreamItem();
                item.read(inProtocol);
                if (item.body == null || item.body.clean_visible == null) {
                    continue;
                }

                String streamId = "";
                if (item.stream_id != null) {
                    streamId = item.stream_id;
                }

                String dateTime = "";
                long epochTime = 0;
                if (item.stream_time != null && item.stream_time.zulu_timestamp != null) {
                    dateTime = item.stream_time.zulu_timestamp;
                    DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
                    epochTime = dtf.parseMillis(dateTime);
                }

                String source = "";
                if (item.source != null) {
                    source = item.source;
                }

                String url = "";
                if (item.abs_url != null) {
                    url = decoder.decode(item.abs_url).toString();
                }

                Map<String, List<Sentence>> parsers = item.body.sentences;
                List<Sentence> sentenceParser = parsers.get(parser);

                String sentencesText = "";
                int sentenceNum = 0;
                if (sentenceParser != null && sentenceParser.size() > 0) {

                    for (Sentence s : sentenceParser) {
                        List<Token> tokens = s.tokens;
                        String sentence = "";
                        for (Token token : tokens) {
                            String tok = token.token;
                            sentence += tok + " ";
                        }
                        sentencesText += sentenceNum + " " + sentence + "\n";
                        sentenceNum++;
                    }
                }

                try {
                    String hourDayDir = outfile.getName().replace(".txt", "");
                    out.write("<DOC>\n");
                    out.write("<DOCNO>" + streamId + "</DOCNO>\n");
                    out.write("<SOURCE>" + source + "</SOURCE>\n");
                    out.write("<URL>" + url + "</URL>\n");
                    out.write("<DATETIME>" + dateTime + "</DATETIME>\n");
                    out.write("<HOURDAYDIR>" + hourDayDir + "</HOURDAYDIR>\n");
                    out.write("<EPOCH>" + epochTime + "</EPOCH>\n");
                    out.write("<TEXT>\n" + sentencesText + "\n</TEXT>\n");
                    out.write("</DOC>\n");
                } catch (Exception e) {
                    System.out.println("Error processing " + infile.getAbsolutePath() + " " + item.stream_id);
                    e.printStackTrace();
                }

            }
        } catch (TTransportException te) {
            if (te.getType() == TTransportException.END_OF_FILE) {
            } else {
                throw te;
            }
        }
        inTransport.close();
        out.close();

    } catch (Exception e) {
        System.out.println("Error processing " + infile.getName());
        e.printStackTrace();
    }
    return results;
}