FileWriter不能写utf-8的原因及解决

Typora绘制思维导图 我们观察一下,其实思维导图就是树状结构的数据嘛,作为程序员,拿语言写树状结构的数据是很平常的事情。而且写代码可比画图省事多了,查阅资料可以知道,有一种`mermaid`语法,就是做这件事情的,支持 UML,甘特图,流程图等。 阅读详情
/*
 * Copyright 2007 nuaa. All rights reserved.
 * This file is by yethyeth, 2007-9-3 9:27:34.
 
*/
package cn.yethyeth.sample.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

// TODO: Auto-generated Javadoc
/**
 *//**
 * 本文件名为FileWriterSubstituteSample,实际上是在寻找FileWriter的替代者。
 * 因为FileWriter在写文件的时候,其编码方式似乎是System.encoding或者System.file.encoding(已经证明FileWriter和FileReader确实使用系统当前默认的编码方式,更多信息包括FileReader的详见http://www.javapractices.com/Topic42.cjp),
 * 在中文win下encoding基本是gb2312,在en的win下基本是iso-8859-1,总之不是utf-8。
 * 所以要创建一个utf-8的文件,用FileWriter是不行的。(FileWriter和FileReader都不支持通过参数指定编码方式,而OutputStreamWriter和InputStreamReader可以。这两个类从名字上就可以看到是字节流和字符流的组合,实际上也是连接两者的桥梁)。 目前不知道如何更改其用来写文件的编码方式,因此对于创建utf-8文件使用如下方式来代替。
 * 
 * 参见:
 * 
http://www.malcolmhardie.com/weblogs/angus/2004/10/23/java-filewriter-xml-and-utf-8/
 
*/
public class FileWriterSubstituteSample {
    
    
/**
     * The main method.
     * 
     * 
@param args
     *            the arguments
     
*/
    
public static void main(String[] args){
        String path
="cn/yethyeth/sample/resources/XML_UTF-8.xml";
        
try {
            OutputStreamWriter out 
= new OutputStreamWriter(new FileOutputStream(path),"UTF-8");
            out.write(
"<?xml version=/"1.0/" encoding=/"utf-8/"?><a>这是测试。</a>");
            out.flush();
            out.close();
            System.out.println(
"success...");
        } 
catch (UnsupportedEncodingException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        } 
catch (FileNotFoundException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        } 
catch (IOException e){
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
【WorkBuddy专栏61】字节的AI打法为什么一直在变——WorkBuddy/CodeBuddy vs 字节Trae/TRAE Work/豆包全维度对比 阅读详情

相关推荐

立创·庐山派-K230-CanMV(嘉楠勘智)开发板通过ATK-ESP8266实现图像识别数据无线传输至原子云

本文详细介绍了如何使用立创·庐山派-K230-CanMV开发板,通过ATK-ESP8266 WIFI模块实现图像识别数据的无线传输至原子云平台。内容包括硬件连接、软件环境搭建、AT指令控制、原子云连接及数据上传的全过程,并提供了实用的调试技巧和常见问题解决方案,为物联网应用开发提供了完整实践指南。

potato的博客 741

Java中FileWriter写入中文乱码

Java中FileWriter写入中文乱码通常是由于“系统向目标文件写入时所使用的编码与目标文件自身的编码不同”解决办法:首先,确保使用JDK11及以上其次,在实例化FileWriter的时候,第二个参数使用指定的文件编码,如UTF-8最后,成功运行。在VsCode中使用新版本JDK时需要指定新版JDK文件位置,找到对应的settings文件进行设置即可。

ax_优快云的博客 7797

ROS开发者的福音:用Anaconda虚拟环境解决Python包冲突(附完整配置流程)

本文为ROS开发者提供了使用Anaconda虚拟环境解决Python包冲突的完整方案。通过分析冲突根源,详细介绍了Miniconda安装、专用环境创建以及核心桥梁包的配置流程,并阐述了“混合环境运行”与“纯虚拟环境构建”两种实战工作流,帮助开发者实现ROS核心与特定Python库的和谐共存,从而提升开发效率和项目可维护性。

weixin_28835789的博客 338

FileWriter无法编码utf-8导致中文乱码

问题描述 FileWriter无法编码utf-8导致中文乱码 原因 FileWriter 默认是用(ISO-8859-1 or US-ASCII)西方编码的,而FileWriter类有getEncoding方法,却没有setEncoding的方法,总之不是UTF-8的。 解决办法 原: File file1 = new File("D:\\TEST.xml"); FileWriter fw = new FileWriter(file1); fw.write("要输入的字符串"); fw.f..

zxw08611的专栏 2447

Linux下用SquareLine Studio开发LVGL界面:从安装到实战的完整避坑指南

本文提供了一份在Linux系统下使用SquareLine Studio开发LVGL图形界面的完整实战指南。内容涵盖从SDL库安装、SquareLine Studio环境配置、界面可视化设计,到工程导出、源码编译及常见错误排查的全流程。重点解析了如何将设计界面无缝集成到Linux开发流程中,并针对嵌入式设备移植提供了关键步骤,旨在帮助开发者高效避坑,快速上手LVGL界面开发。

egg99的博客 905

在没有信用卡的情况下怎么申请谷歌云(Google Cloud)?

这笔额度足够用来跑一台云服务器、部署小型网站,甚至可以尝试 AI、机器学习等项目。但问题来了——想要拿到这 300 美元,你必须先通过支付方式验证。默认选项就是绑定一张国际信用卡(Visa、MasterCard 之类),然而不少人没有信用卡,或者信用卡无法支持国际支付,结果就卡在注册第一步。很多人会疑惑:既然是送额度,为什么还要绑卡?原因其实很简单:谷歌需要确认你是真实用户,而不是批量注册薅羊毛;通过支付验证,后续如果你用完 300 美元额度,可以直接进行付费使用;

m0_74824483的博客 5653

字符流FileReader和FileWriter

字符输入和输出流

weixin_50263454的博客 1136

2026年美赛数学建模竞赛 MCM B题:使用太空电梯系统建立月球殖民地 问题一 月球殖民地材料运输的三种场景建模 详细解题思路和代码

如果运输系统不能完美工作(例如,系绳摆动、火箭失败、电梯故障等),你的解决方案在多大程度上会发生变化?技术可行性:三种方案在技术上都是可行的,但挑战不同 经济性:混合方案在长期视角下最具成本效益 时间效率:并行运输可以显著缩短总建设时间环境影响:太空电梯的环境优势明显,混合方案可平衡需求风险分散:混合方案提供了天然的风险分散机制

YOLO 615

Java FileWriter无法编码utf-8 转换方法

参考自:Java FileWriter无法编码utf-8 转换方法 原本想通过文件追加的方式,向.txt或者.json文件(其他也类似)结尾添加新的文本,开始通过FileWriter追加,但是中文追加后却成了乱码。 查了一圈下来结论是:Java FileWriter 默认是用(ISO-8859-1 or US-ASCII)西方编码的,而FileWriter类没有setEncoding的方法。希望通...

weixin_44761910的博客 2328

Spring AI 实战:第七章、Spring AI Advisor机制之记忆大师

从金鱼到最强大脑通过 Spring AI 的记忆功能,我们成功让 AI:记住了用户身份实现了多用户隔离做到了持久化存储最终效果用户:“和上次一样” → AI 秒懂用户:“你知道我的名字吗?” → AI:“当然,张三!AI的进化路线🐟金鱼脑 →🧠最强大脑 →🏛️记忆宫殿管理员。

liaokailin的专栏 1516

12、知识图谱数据处理与推理全解析

本文深入解析了知识图谱中的数据处理与推理技术,涵盖SHACL的多种约束类型(如值约束、范围约束、字符串约束、逻辑约束等)及其在数据质量控制中的应用,并介绍了常用的SHACL工具与实际案例。文章对比了SPARQL与SHACL的特点,探讨了RDF(S)的局限性,引出表达能力更强的OWL和OWL2语言及其在语义网和生物医学等领域的应用。此外,还阐述了规则在知识表示中的作用,包括产生式规则和Datalog规则,并总结了知识图谱中推理的重要性与典型流程,为构建高质量、可推理的知识图谱提供了全面的技术指导。

zz67890的博客 135

96.InputStreamReader,OutputStreamWriter , FileReader指定UTF-8编码格式

package com.itheima.convertedio; import java.io.*; import java.nio.charset.Charset; public class ConverteDemo1 { public static void main(String[] args) throws IOException { //method1(); //mthode2(); FileReader fr=new FileRead.

qq_31426093的博客 2735

uniapp [全端兼容] - 最新详细实现拍摄视频录像并可播放预览视频,调起本机摄像头开启录像录制完毕后保存到本机临时存放,可对拍摄的视频进行压缩处理减少文件大小不损失画质,详解录制视频并读取播放!

uni-app,h5移动端网页,微信小程序,支付宝小程序,Android安卓,苹果ios,app,nvue,录视频,拍视频,拍摄录制视频后上传服务器,调起摄像头录视频并可预览,录视频上传,录像,uniapp录制视频并上传,录制视频并保存到本地设备,如何本地保存并播放预览,提供给用户观看MP4视频录像并上传到后端服务器完整功能源码,视频压缩,mp4文件,删除视频,录像后怎么预览,临时视频文件怎么减少压缩大小,视频压缩及上传,自己录视频并生成可播放的文件,录视频并能打开查看,视频压缩后上传,本机相册,录完怎么预

🏆 前端领域优质创作者 1万+

filewriter 设置编码_FileWriter不能写utf-8的原因及解决

packagecn.yethyeth.sample.io;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStreamWriter;importjava.io.UnsupportedEncodingExcept...

weixin_39889481的博客 1333

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

filewriter 设置编码,将编码设置为FileWriter的UTF-8

Below is my code, it is intended to take two .ckl files, compare the two, add the new items and create a new merged file. The program executes correctly when run in Netbeans however, when executing th...

weixin_39600510的博客 1194

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

filewriter 设置编码_将编码设置为FileWriter的UTF-8

Below is my code, it is intended to take two .ckl files, compare the two, add the new items and create a new merged file. The program executes correctly when run in Netbeans however, when executing th...

weixin_39723655的博客 1357

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

filewriter 设置编码_使用FileWriter(Java)以UTF-8编写文件?

I have the following code however, I want it to write as a UTF-8 file to handle foreign characters. Is there a way of doing this, is there some need to have a parameter?I would really appreciate your...

weixin_39671509的博客 1395

filewriter 设置编码_将FileWriter的编码设置为UTF-8

下面是我的代码,它打算获取两个.ckl文件,比较两个文件,添加新项目并创建一个新的合并文件。该程序在Netbeans中运行时可以正确执行,但是,当执行.jar时,该程序似乎未使用UTF-8编码文件。我对编程很陌生,想知道在什么地方或如何执行这种编码?**我删除了Swing代码和其他行,以便仅显示我的方法,该方法完成所有比较和合并。public void mergeFiles(File[] file...

weixin_39709194的博客 3125

filewriter 设置编码,使用FileWriter(Java)以UTF-8编写文件?

I have the following code however, I want it to write as a UTF-8 file to handle foreign characters. Is there a way of doing this, is there some need to have a parameter?I would really appreciate your...

weixin_42300113的博客 1039

使用FileWriter可以写UTF-8的解决方法

为什么80%的码农都做不了架构师?>>> ...

weixin_34060299的博客 2069

FileWriter不能写utf-8

今天碰到个问题,统计数据,用FileWriter写到unix系统的一个文件中,然后程序导入到另外一个表中,总是有乱码出现。数据库驱动的编码是utf-8,转了好几次也不行,怀疑是写文件的问题。上网google了下,原来FileWriter不能写utf-8,google就是好。 package cn.yethyeth.sample.io; import java.io.FileNotFoundExce...

若水汪洋的java学习博客 345

dom4j UTF-8编码的解决

这几天开始学习dom4j,在网上找了篇文章就开干了,上手非常的快,但是发现了个问题就是无法以UTF-8保存xml文件,保存后再次读出的时候会报“Invalid byte 2 of 2-byte UTF-8 sequence.”这样一个错误,检查发现由dom4j生成的这个文件,在使用可正确处理XML编码的任何的编辑器中中文成乱码,从记事本查看并不会出现乱码会正确显示中文。让我很是头痛。试着使用GBK

douxinchun的专栏 1343
上一篇: 利用JAXB进行xml和javabean之间转换
下一篇: 设置checkbox复选框为readonly只读的两种方式
Johnny__Tang
博客等级 码龄18年 9粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值