读取txt文件内容到String

读取TXT文件中文本并存入数组(Java) 读取TXT文件中文本并存入数组中 ​ 当我们看到这样的txt文本,必然好奇如何读取文本的数据。如何读取数据很简单,只要设计一个有关函数,分行读取即可!那么如何将数据存入数组里呢?只要将获取的数据存入StringBuilder里,将带有数据的StringBuilder变量变成String类型数组,再用String类型数组读取即可。 读取txt文件 ​ 在txtToString(File file)函数中,我们建立一个StringBuilder类型的result变量,这个result变量是需要存储所需的txt 阅读详情
package com.example.demo.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

txt文档转化为String 将.txt文档转化为String类型 具体代码如下: package IndexSearch; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * 将txt的路径,将txt文档转换为String内容 * @author jean * */ public class TextFileExchange { //将txt转换为String public static String readTxt(String path) throws IOException{ StringBuffer content = new StringBuffer(""); //文档内容 try { FileReader reader = new FileReader(path); BufferedReader br = new BufferedReader(reader); String s1 = null; while((s1 = br.readLine()) != null) { content.append(s1+"\r"); } br.close(); reader.close(); }catch(IOException e) { e.printStackTrace(); } return content.toString().trim(); } public static void main(String[] args) { System.out.println(IndexPath.Index_File_Path); String path = IndexPath.Index_File_Path; try { String temp = readTxt(path); System.out.println(temp); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } 立即下载

相关推荐

java io读取文件到String

public static String loadAFileToStringDE1(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new BufferedInputStream( new FileInputStream(f) ); long contentLength = f.length(); ByteArrayOutputStream outstream = new ByteArrayOutputStream( contentLength > 0 ? (int) contentLength : 1024); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { outstream.write(buffer, 0, len); } outstream.close(); ret = outstream.toString(); //byte[] ba = outstream.toByteArray(); //ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法1用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE2(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new FileInputStream(f) ; long contentLength = f.length(); byte[] ba = new byte[(int)contentLength]; is.read(ba); ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法2用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE3(File f) throws IOException { long beginTime = System.currentTimeMillis(); BufferedReader br = null; String ret = null; try { br = new BufferedReader(new FileReader(f)); String line = null; StringBuffer sb = new StringBuffer((int)f.length()); while( (line = br.readLine() ) != null ) { sb.append(line).append(LINE_BREAK); } ret = sb.toString(); } finally { if(br!=null) {try{br.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法3用时"+ (endTime-beginTime) + "ms"); return ret; } 3个方法去读取一个大于50M的文件,当不设置jvm参数时都OutofMemery,当设置-Xmx128M时。只有方法3 可以通过,设置到-Xmx256M时也只有方法3可以通过,干脆设置512M,都可以了,运行时间如果正常的话一般都在4~5S

MTK metadata中AF模块的移除与配置调整

本文详细介绍了在MTK平台Camera开发中如何移除metadata中的AF(自动对焦)模块。通过系统清理MTK_CONTROL_AF_REGIONS、MTK_CONTROL_MAX_REGIONS等关键配置项,并调整对焦模式及硬件特性声明,确保定制化设备在禁用自动对焦功能后的稳定运行。

q1w3e5r7t9y的博客 570

Revit二次开发之双事件:空闲事件与DocumentChanged事件

对以下文章所展示的代码进行了修改,当前展示的代码可直接复制使用。 由于本人初学,下列语言为个人理解,如有错误请指正。   《引用1》中: 使用模态对话框,或者尽量保证事件在ExternalCommand的Execute函数或者ExternalApplication的OnStartup函数里面注册。 如果一定要使用非模态对话框,那么请使用ExternalEvent事件的Raise函数,强迫...

一个Revit二次开发的实习生 6147

VS2017配置PCL1.9.1 for win10(超详细)

准备工作 VS2017 自行下载 PCL1.9.1 点击链接跳转Github下载,根据自己的环境选择 win64或win32,作者下载的是:PCL-1.9.1-AllInOne-msvc2017-win64.exepcl-1.9.1-pdb-msvc2017-win64.zip 安装PCL 双击点开PCL-1.9.1-AllInOne-msvc2017-win64.exe,选择Add PCL to the system PATH for all users, 更改安装路径,E:\Progra

malapoa的博客 1146

Mamba vs YOLO:目标检测选型指南(附实际项目对比)

本文深入对比了Mamba和YOLO在目标检测领域的性能差异与应用场景。通过实际项目数据,分析了两者在城市交通监控、工业质检等场景下的表现,提供了详细的选型指南和部署优化建议,帮助开发者根据实时性、精度等需求选择最适合的解决方案。

weixin_29062255的博客 368

基于高频变压器的隔离式推挽栅极驱动电路

摘要:本文介绍了一种基于高频变压器的隔离式推挽栅极驱动电路,通过变压器实现电气隔离,为功率MOS管提供可靠驱动信号。电路包含输入侧PWM信号处理、变压器磁耦合隔离传输以及副边驱动逻辑等关键部分,利用电阻电容网络控制开关速度并防止误触发。该隔离驱动方案广泛应用于高压开关电源、新能源汽车电机控制器、光伏逆变器和工业变频器等需要高电压隔离及抗干扰能力的电力电子设备中,有效保障系统安全性和可靠性。

qq_37999850的博客 483

探索如何利用CST和ADS进行DDR的SIPI联合仿真

本文系统介绍了CST和ADS两款工具进行DDR信号完整性/电源完整性(SI/PI)联合仿真的方法。CST采用工作室协同方式,通过PCB布局导入、材料设置、模型分配等步骤,重点分析了电源阻抗优化和信号波形质量。ADS则利用SIPro、PIPro等专用工具,突出系统级验证和自动化优化功能。两者各有优势:CST擅长3D结构精确建模,ADS更适于快速系统验证。文章建议可根据项目需求混合使用两种工具,并提供了模型简化、频带选择等实用技巧。通过对比分析,为工程师选择仿真工具提供了决策参考。

一只豌豆象的博客 1150

AI测试:手把手教你用AI做Web自动化测试「喂饭教程」

本文介绍了基于MCP协议和使用 mcp-use + playwright-mcp 构建智能Web自动化测试框架的实践方法。通过整合大语言模型的理解能力与测试工具可靠性,该方案支持用自然语言描述测试流程,自动转换为可执行的测试步骤,提升测试效率,支持复杂场景和多步骤流程,为自动化测试提供了新思路。

blues_C的博客 1280

FPGA设计-Vivado的Off-Chip Termination设置问题

经常遇到在FPGA设计时,很多人很迷惑这些关于硬件的终端匹配怎么设置,Vivado的Off-Chip Termination设置问题,这里就详细说一下这个问题。

whm128的博客 2725

深度学习工具包 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")

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

上一篇: 字符串写入txt文件
下一篇: 获取文件夹下的所有文件
脾气很倔呢
博客等级 码龄9年 190粉丝 309原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值