`
ddandyy
  • 浏览: 211385 次
  • 性别: Icon_minigender_1
  • 来自: 目前上海
社区版块
存档分类
最新评论

read file to 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


	public static String ReadFileToString(String url) {
		StringBuffer str = new StringBuffer();
		BufferedReader in = null;
		File inputFile = null;
		try {
			inputFile = new File(url);

			in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "GB2312"));
			String line = null;
			str = new StringBuffer((int) inputFile.length());

			while ((line = in.readLine()) != null) {
				str.append(line);
			}
			in.close();
		}
		catch (FileNotFoundException e2) {
			try {
				if (!new File(inputFile.getParent()).exists())
					new File(inputFile.getParent()).mkdirs();
				inputFile.createNewFile();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		catch (IOException e3) {
			e3.printStackTrace();
		}
		return str.toString();
	}
分享到:
评论
1 楼 阿浊I 2010-01-13  
试了,不行,不知道为什么
读得是60M的文件

相关推荐

    MVel 2.0.15 doc

    MVEL is an expression language – similar to OGNL – and a templating engine. I’d like to give you ... You can use something like FileUtils.readFileToString(File) to read a template file into a String.

    commons-io-2.CHM

    readFileToString:将文件内容作为字符串返回。 readLines:将文件内容按行返回到一个字符串数组中。 size:返回文件或目录的大小。 write:将字符串内容直接写到文件中。 writeByteArrayToFile:将字节数组内容...

    readTxtFile.java

    java 代码,将txt文件的内容包括标点符号,换行符,读取到字符串中.

    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( ...

    Apache提供的commons_io组件

    static String readFileToString(File file):读取文件内容,并返回一个String; static void writeStringToFile(File file, String data):将内容content写入到file中; static void ...

    File_实用案例_实现文件拷贝_FileCopy.java

    String parent = to_file.getParent(); // The destination directory if (parent == null) // If none, use the current directory parent = System.getProperty("user.dir"); File dir = new File(parent); /...

    Text-File-for-String-Manipulation.rar_it

    This program is used to manipulate text by reading the content of a text file and read it line by line while extracting the data in it.

    Java文件处理工具类--FileUtil

    * Write string content to local file using given character encoding. * * @param fileName - * local file name will write to * @param content * String text * @param encoding * the ...

    H2OUVE_100.0.9.2.zip

    -gi <ImageFile> <File> Read image file, and generate variable information to file. -si <File> <ImageFile> Modify variable with specified file on image file. -gk <File> Generate BIOS Hotkey setting...

    Exception in thread “main” javax.imageio.IIOException: Can’t read input file!

    Exception in thread “main” javax.imageio.IIOException: Can’t read input file!:无法读取输入文件! 原可以从两个方面分析: 路径中文乱码问题 target/classes文件夹中并没有找到图片 加粗样式看下代码: ...

    WAV文件的读写接口类,依赖标准C++库

    bool read(const string &filename); private: // Read wav file header bool read_header(const string &filename); private: shared_ptr<Wave_header> header; unique_ptr[]> data; };

    thumbnailator-0.4.8

    * .toFile(String 新图片路径) * .sourceRegion(Positions.BOTTOM_RIGHT,int 宽度,int 高度) Positions.BOTTOM_RIGHT 位置 * .watermark(位置 Positions.TOP_RIGHT,ImageIO.read(new File(水印图)),透明度 0.9f) ...

    java解析txt

    public static void readTxtFile(String filePath){ try { String encoding="GBK"; File file=new File(filePath); if(file.isFile() && file.exists()){ //判断文件是否存在 InputStreamReader read = ...

    操作系统之文件系统设计一个n 个用户的文件系统,每次用户可保存m 个文件,用户在一次运行中只能打开一个文件,对文件必须设置保护措施。至少要有create,delete,open,close,read,write等命令

    实验要求:设计一个n 个用户的文件系统,每次用户可保存m 个文件,用户在一次运行中只能打开一个文件,对文件必须设置保护措施。...void TForm1::InserMFD(String User, String FilePointer,MFD &Mfd)

    UE(官方下载)

    You can use these functions to insert a file into the current file, delete the active file, send the file through email, or insert a string into the file at every specified increment HTML preview ...

    MFC文件操作

    file.WriteString(strValue); //读取数据 CString strRead; file.ReadString(strRead); 当文件存在多行数据需要逐行读取时,可用函数BOOL CStdioFile::ReadString(CString& rString),当遇到"\n "时读取截断,如果...

    Linux下的rar解压缩工具

    Linux下的rar解压缩工具: ... x@ Read file names to exclude from stdin x@<list> Exclude files listed in specified list file y Assume Yes on all queries z[file] Read archive comment from file

    android 上传文件

    String sourceid = fileService.find(file); Socket socket = new Socket("192.168.1.157", 7878); OutputStream outStream = socket.getOutputStream(); String head = "Content-Length="+ file....

    Type of dat

    FS := TFileStream.Create( // to read data file DataFile, fmOpenRead); RS := TFileStream.Create( // to write res file ResFile, fmCreate); { Create res file header - all zeros except for ...

    java压缩文件源码--ZipUtils

    log("unzip to "+getFileName(file.getPath())); FileOutputStream fos = new FileOutputStream(getFileName(file.getPath())+File.separator+newDir(file, entry.getName())); dest = new ...

Global site tag (gtag.js) - Google Analytics