
可以通过BufferedReader 流的形式进行流读取,之后通过readLine方法获取到流每行的内容。
BufferedReader bre = null;
try {
String file = "D:/test/testtxt";
bre = new BufferedReader(new FileReader(file));//此时获取到的bre就是整个文件的缓存流
while ((str = brereadLine())!= null) // 判断最后一行不存在,为空结束循环
{
Systemoutprintln(str);//原样输出读到的内容
};
备注: 上面的bre就是提问者需要的流。流用完之后必须close掉,如上面的就应该是:breclose(),否则bre流会一直存在,直到程序运行结束。
1、stream一般是指文件指针,这里stream!=NULL的意思就是文件指针不为空的情况。
2、编程语言中的stream
重要运算符
在C++,C#,java等编程语言中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O,stream这个类有两个重要的运算符:
1、插入器(<<)
向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<"Write Stdout"<<'n';就表示把字符串"Write Stdout"和换行字符('n')输出到标准输出流。
2、析取器(>>)
从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示从标准输入流中读取一个指定类型(即变量x的类型)的数据。
在C++中,对文件的 *** 作是通过stream的子类fstream(file stream)来实现的,所以,要用这种方式 *** 作文件,就必须加入头文件fstreamh。下面就把此类的文件 *** 作过程一一道来。
打开文件
在fstream类中,有一个成员函数open(),就是用来打开文件的,其原型是:
void open(const char filename,int mode,int access);
参数:
filename: 要打开的文件名
mode: 要打开文件的方式
access: 打开文件的属性
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:
ios::app: 以追加的方式打开文件
ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性
ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
ios::in: 文件以输入方式打开
ios::out: 文件以输出方式打开
ios::nocreate: 不建立文件,所以文件不存在时打开失败
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc: 如果文件存在,把文件长度设为0
可以用“或”把以上属性连接起来,如ios::out|ios::binary
// 注:现在C++标准库不支持nocreate和noreplace,以前的旧版本可以用
打开文件的属性取值是:
0:普通文件,打开访问
1:只读文件
2:隐含文件
4:系统文件
可以用“或”或者“+”把以上属性连接起来 ,如3或1|2就是以只读和隐含属性打开文件。
例如:以二进制输入方式打开文件c:configsys
fstream file1;
file1open("c:configsys",ios::binary|ios::in,0);
如果open函数只有文件名一个参数,则是以读/写普通文件打开,即:
file1open("c:configsys");<=>file1open("c:configsys",ios::in|ios::out,0);
另外,fstream还有和open()一样的构造函数,对于上例,在定义的时候就可以打开文件了:
fstream file1("c:configsys");
特别提出的是,fstream有两个子类:ifstream(input file stream)和ofstream(outpu file stream),ifstream默认以输入方式打开文件,而ofstream默认以输出方式打开文件。
ifstream file2("c:pdosdef");//以输入方式打开文件
ofstream file3("c:x123");//以输出方式打开文件
所以,在实际应用中,根据需要的不同,选择不同的类来定义:如果想以输入方式打开,就用ifstream来定义;如果想以输出方式打开,就用ofstream来定义;如果想以输入/输出方式来打开,就用fstream来定义。
关闭文件
打开的文件使用完成后一定要关闭,fstream提供了成员函数close()来完成此 *** 作,如:file1close();就把file1相连的文件关闭。
读写文件
读写文件分为文本文件和二进制文件的读取,对于文本文件的读取比较简单,用插入器和析取器就可以了;而对于二进制的读取就要复杂些,下要就详细的介绍这两种方式
1、文本文件的读写
文本文件的读写很简单:用插入器(<<)向文件输出;用析取器(>>)从文件输入。假设file1是以输入方式打开,file2以输出打开。示例如下:
file2<<"I Love You";//向文件写入字符串"I Love You"
int i;
file1>>i;//从文件输入一个整数值。
这种方式还有一种简单的格式化能力,比如可以指定输出为16进制等等,具体的格式有以下一些
*** 纵符 功能 输入/输出
dec 格式化为十进制数值数据 输入和输出
endl 输出一个换行符并刷新此流 输出
ends 输出一个空字符 输出
hex 格式化为十六进制数值数据 输入和输出
oct 格式化为八进制数值数据 输入和输出
//setprecision(int p) 设置浮点数的精度位数 输出
(setpxecision应该为setprecision,使用时需要包含头文件:#include <iomaniph>)
//比如要把123当作十六进制输出:file1<<hex<<123;要把31415926以5位精度输出:file1<<setprecision(5)<<31415926。
比如要把123当作十六进制输出:file1<<hex<<123;要把31415926以5位精度输出:file1<<setprecision(5)<<31415926。
2、二进制文件的读写
①put()
put()函数向流写入一个字符,其原型是ofstream &put(char ch),使用也比较简单,如file1put('c');就是向流写一个字符'c'。
②get()
get()函数比较灵活,有3种常用的重载形式:
一种就是和put()对应的形式:ifstream &get(char &ch);功能是从流中读取一个字符,结果保存在引用ch中,如果到文件尾,返回空字符。如file2get(x);表示从文件中读取一个字符,并把读取的字符保存在x中。
另一种重载形式的原型是: int get();这种形式是从流中返回一个字符,如果到达文件尾,返回EOF,如x=file2get();和上例功能是一样的。
还有一种形式的原型是:ifstream &get(char buf,int num,char delim='n');这种形式把字符读入由 buf 指向的数组,直到读入了 num 个字符或遇到了由 delim 指定的字符,如果没使用 delim 这个参数,将使用缺省值换行符'n'。例如:
file2get(str1,127,'A');//从文件中读取字符到字符串str1,当遇到字符'A'或读取了127个字符时终止。
③读写数据块
要读写二进制数据块,使用成员函数read()和write()成员函数,它们原型如下:
read(unsigned char buf,int num);
write(const unsigned char buf,int num);
read()从文件中读取 num 个字符到 buf 指向的缓存中,如果在还未读入 num 个字符时就到了文件尾,可以用成员函数 int gcount();来取得实际读取的字符数;而 write() 从buf 指向的缓存写 num 个字符到文件中,值得注意的是缓存的类型是 unsigned char ,有时可能需要类型转换。
例:
unsigned char str1[]="I Love You";
int n[5];
ifstream in("xxxxxx");
ofstream out("yyyyyy");
outwrite(str1,strlen(str1));//把字符串str1全部写到yyyyyy中
inread((unsigned char)n,sizeof(n));//从xxxxxx中读取指定个整数,注意类型转换
inclose();outclose();
检测EOF
成员函数eof()用来检测是否到达文件尾,如果到达文件尾返回非0值,否则返回0。原型是int eof();
例: if(ineof())ShowMessage("已经到达文件尾!");
文件定位
和C的文件 *** 作方式不同的是,C++ I/O系统管理两个与一个文件相联系的指针。一个是读指针,它说明输入 *** 作在文件中的位置;另一个是写指针,它下次写 *** 作的位置。每次执行输入或输出时,相应的指针自动变化。所以,C++的文件定位分为读位置和写位置的定位,对应的成员函数是 seekg()和 seekp(),seekg()是设置读位置,seekp是设置写位置。它们最通用的形式如下:
istream &seekg(streamoff offset,seek_dir origin);
ostream &seekp(streamoff offset,seek_dir origin);
streamoff定义于 iostreamh 中,定义有偏移量 offset 所能取得的最大值,seek_dir 表示移动的基准位置,是一个有以下值的枚举:
ios::beg: 文件开头
ios::cur: 文件当前位置
ios::end: 文件结尾
这两个函数一般用于二进制文件,因为文本文件会因为系统对字符的解释而可能与预想的值不同。
例:
file1seekg(1234,ios::cur);//把文件的读指针从当前位置向后移1234个字节
file2seekp(1234,ios::beg);//把文件的写指针从文件开头向后移1234个字节
stream
1 小河,溪流
2 流;流动[(+of)]
People kept coming in streams
人们川流不息地到来。
3 光线;(光的)束,道
4 潮流;趋势[S1]
He always goes with the stream
他总是顺应潮流。
5 英将学生按能力分成的组
vi[Q]
1 流,流动;淌
The pipe broke and water streamed onto the floor
水管破裂,水流到地板上。
2 涌入,涌进;川流不息
Blood streamed from the wound
血从伤口流出。
3 飘动,飘扬
vt
1 流出;涌出
Her nose streamed blood
她的鼻子淌血。
2 使飘动
3 英将(学生)按能力分组
以上结果由 Dreye译典通字典 提供
在C#中读取20GB以上的大文件,建议使用流(Stream)来读取,以避免一次性加载整个文件到内存中而导致内存不足的问题。
以下是一种使用流来读取大文件的示例代码:
using (FileStream fs = new FileStream(@"C:\path\to\large\filetxt", FileModeOpen, FileAccessRead))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
string line;
while ((line = srReadLine()) != null)
{
// 处理每一行数据的逻辑
}
}
}
}
在这个代码示例中,我们使用了三个流对象:
FileStream:用于打开大文件并将其作为输入流
BufferedStream:用于加快数据的读取速度,通过使用一个内部缓存来减少对硬盘的读取次数
StreamReader:用于按行读取文本数据
在while循环中,我们可以处理每一行数据的逻辑。由于只读取了一行数据,因此内存占用较小,可以避免因为文件过大导致内存溢出的问题。
需要注意的是,在处理大文件时,为了保证性能,最好使用异步读取方式。这可以通过将StreamReader对象的ReadLine方法替换为异步版本ReadLineAsync来实现。
函数原型: size_t fread( void buffer, size_t size, size_t count, FILE stream );
参 数:
1用于接收数据的地址(指针)(buffer)
2单个元素的大小(size) :单位是字节而不是位,例如读取一个整型数就是2个字节
3元素个数(count)
4提供数据的文件指针(stream)
返回值:成功读取的元素个数
给你一个例子 你看一下
#include <stdioh>
void main( void )
{
FILE stream;
char list[30];
int i, numread, numwritten;
/ Open file in text mode: /
if( (stream = fopen( "freadout", "w+t" )) != NULL )
{
for ( i = 0; i < 25; i++ )
list[i] = (char)('z' - i);
/ Write 25 characters to stream /
numwritten = fwrite( list, sizeof( char ), 25, stream );
printf( "Wrote %d items\n", numwritten );
fclose( stream );
}
else
printf( "Problem opening the file\n" );
if( (stream = fopen( "freadout", "r+t" )) != NULL )
{
/ Attempt to read in 25 characters /
numread = fread( list, sizeof( char ), 25, stream );
printf( "Number of items read = %d\n", numread );
printf( "Contents of buffer = %25s\n", list );
fclose( stream );
}
else
printf( "File could not be opened\n" );
}
1、CPU频率,CPU信息:/proc/cpuinfo和/proc/stat
通过读取文件/proc/cpuinfo系统CPU的类型等多种信息。
读取/proc/stat 所有CPU活动的信息来计算CPU使用率
下面我们就来讲讲如何通过代码来获取CPU频率:
复制代码 代码如下:
package comorangecpu;
import javaioBufferedReader;
import javaioFileNotFoundException;
import javaioFileReader;
import javaioIOException;
import javaioInputStream;
public class CpuManager {
// 获取CPU最大频率(单位KHZ)
// "/system/bin/cat" 命令行
// "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" 存储最大频率的文件的路径
public static String getMaxCpuFreq() {
String result = "";
ProcessBuilder cmd;
try {
String[] args = { "/system/bin/cat",
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
cmd = new ProcessBuilder(args);
Process process = cmdstart();
InputStream in = processgetInputStream();
byte[] re = new byte[24];
while (inread(re) != -1) {
result = result + new String(re);
}
inclose();
} catch (IOException ex) {
exprintStackTrace();
result = "N/A";
}
return resulttrim();
}
// 获取CPU最小频率(单位KHZ)
public static String getMinCpuFreq() {
String result = "";
ProcessBuilder cmd;
try {
String[] args = { "/system/bin/cat",
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" };
cmd = new ProcessBuilder(args);
Process process = cmdstart();
InputStream in = processgetInputStream();
byte[] re = new byte[24];
while (inread(re) != -1) {
result = result + new String(re);
}
inclose();
} catch (IOException ex) {
exprintStackTrace();
result = "N/A";
}
return resulttrim();
}
// 实时获取CPU当前频率(单位KHZ)
public static String getCurCpuFreq() {
String result = "N/A";
try {
FileReader fr = new FileReader(
"/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
BufferedReader br = new BufferedReader(fr);
String text = brreadLine();
result = texttrim();
} catch (FileNotFoundException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
}
return result;
}
// 获取CPU名字
public static String getCpuName() {
try {
FileReader fr = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fr);
String text = brreadLine();
String[] array = textsplit(":s+", 2);
for (int i = 0; i < arraylength; i++) {
}
return array[1];
} catch (FileNotFoundException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
}
return null;
}
}
2、内存:/proc/meminfo
复制代码 代码如下:
public void getTotalMemory() {
String str1 = "/proc/meminfo";
String str2="";
try {
FileReader fr = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
while ((str2 = localBufferedReaderreadLine()) != null) {
Logi(TAG, "---" + str2);
}
} catch (IOException e) {
}
}
3、Rom大小
复制代码 代码如下:
public long[] getRomMemroy() {
long[] romInfo = new long[2];
//Total rom memory
romInfo[0] = getTotalInternalMemorySize();
//Available rom memory
File path = EnvironmentgetDataDirectory();
StatFs stat = new StatFs(pathgetPath());
long blockSize = statgetBlockSize();
long availableBlocks = statgetAvailableBlocks();
romInfo[1] = blockSize availableBlocks;
getVersion();
return romInfo;
}
public long getTotalInternalMemorySize() {
File path = EnvironmentgetDataDirectory();
StatFs stat = new StatFs(pathgetPath());
long blockSize = statgetBlockSize();
long totalBlocks = statgetBlockCount();
return totalBlocks blockSize;
}
4、sdCard大小
复制代码 代码如下:
public long[] getSDCardMemory() {
long[] sdCardInfo=new long[2];
String state = EnvironmentgetExternalStorageState();
if (EnvironmentMEDIA_MOUNTEDequals(state)) {
File sdcardDir = EnvironmentgetExternalStorageDirectory();
StatFs sf = new StatFs(sdcardDirgetPath());
long bSize = sfgetBlockSize();
long bCount = sfgetBlockCount();
long availBlocks = sfgetAvailableBlocks();
sdCardInfo[0] = bSize bCount;//总大小
sdCardInfo[1] = bSize availBlocks;//可用大小
}
return sdCardInfo;
}
5、电池电量
复制代码 代码如下:
private BroadcastReceiver batteryReceiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
int level = intentgetIntExtra("level", 0);
// level加%就是当前电量了
}
};
registerReceiver(batteryReceiver, new IntentFilter(IntentACTION_BATTERY_CHANGED));
6、系统的版本信息
复制代码 代码如下:
public String[] getVersion(){
String[] version={"null","null","null","null"};
String str1 = "/proc/version";
String str2;
String[] arrayOfString;
try {
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(
localFileReader, 8192);
str2 = localBufferedReaderreadLine();
arrayOfString = str2split("s+");
version[0]=arrayOfString[2];//KernelVersion
localBufferedReaderclose();
} catch (IOException e) {
}
version[1] = BuildVERSIONRELEASE;// firmware version
version[2]=BuildMODEL;//model
version[3]=BuildDISPLAY;//system version
return version;
}
7、mac地址和开机时间
复制代码 代码如下:
public String[] getOtherInfo(){
String[] other={"null","null"};
WifiManager wifiManager = (WifiManager) mContextgetSystemService(ContextWIFI_SERVICE);
WifiInfo wifiInfo = wifiManagergetConnectionInfo();
if(wifiInfogetMacAddress()!=null){
other[0]=wifiInfogetMacAddress();
} else {
other[0] = "Fail";
}
other[1] = getTimes();
return other;
}
private String getTimes() {
long ut = SystemClockelapsedRealtime() / 1000;
if (ut == 0) {
ut = 1;
}
int m = (int) ((ut / 60) % 60);
int h = (int) ((ut / 3600));
return h + " " + mContextgetString(Rstringinfo_times_hour) + m + " "
+ mContextgetString(Rstringinfo_times_minute);
}
JexcelApi 的jar文件版本和你机器上的JDK版本不一致,或者说是JexcelApi的JDK版本比你机器上的JDK版本高,导致JexcelApi的class文件(jar)不能在你本机上使用,建议你下载个最新的JDK版本
以上就是关于JAVA:已知获取文件的输出流ouputStream,怎么转换为文件全部的内容,包括:JAVA:已知获取文件的输出流ouputStream,怎么转换为文件、C语言问题stream!=NULL、请问有些软件里面说的stream版什么意思等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)