当前位置: 首页>>代码示例>>Golang>>正文


Golang File.Name方法代码示例

本文整理汇总了Golang中os.File.Name方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Name方法的具体用法?Golang File.Name怎么用?Golang File.Name使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os.File的用法示例。


在下文中一共展示了File.Name方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: dirList

func dirList(w http.ResponseWriter, f *os.File) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if dirs, err := f.Readdir(-1); err == nil {
		files := make([]map[string]string, len(dirs)+1)
		files[0] = map[string]string{
			"name": "..", "href": "..", "size": "-", "mtime": "-",
		}
		for i, d := range dirs {
			href := d.Name()
			if d.IsDir() {
				href += "/"
			}
			files[i+1] = map[string]string{
				"name":  d.Name(),
				"href":  href,
				"size":  formatSize(d),
				"mtime": d.ModTime().Format("2006-01-02 15:04:05"),
			}
		}
		reloadCfg.dirListTmpl.Execute(w, map[string]interface{}{
			"dir":   f.Name(),
			"files": files,
		})
	}
}
开发者ID:jayvansantos,项目名称:http-watcher,代码行数:25,代码来源:http-watcher.go

示例2: dmndBlastXFine

func dmndBlastXFine(queries *os.File, outFilename, fineFilename string) error {

	cmd := exec.Command(
		flagDmnd,
		"blastx",
		"--sensitive",
		"-d", fineFilename,
		"-q", queries.Name(),
		"--threads", s(flagGoMaxProcs),
		"-a", outFilename,
		"--compress", "0",
		"-c", "1",
		"--top", s(flagFineDmndMatch))
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout

	err := mica.Exec(cmd)
	if err != nil {
		return fmt.Errorf("Error using diamond to blast coarse db: %s\n", err)
	}
	if !flagDmndOutput {
		daaFile, err := os.Open(outFilename)
		if err != nil {
			return fmt.Errorf("Error opening diamond output: %s\n", err)
		}
		tabularFile, err := convertDmndToBlastTabular(daaFile)
		if err != nil {
			return fmt.Errorf("Error converting diamond output: %s\n", err)
		}
		os.Rename(tabularFile.Name(), outFilename)

	}

	return nil
}
开发者ID:jameslz,项目名称:MICA,代码行数:35,代码来源:diamond.go

示例3: CreatePool

// CreatePool is the programmatic example of "dmsetup create".
// It creates a device with the specified poolName, data and metadata file and block size.
func CreatePool(poolName string, dataFile, metadataFile *os.File, poolBlockSize uint32) error {
	task, err := TaskCreateNamed(deviceCreate, poolName)
	if task == nil {
		return err
	}

	size, err := GetBlockDeviceSize(dataFile)
	if err != nil {
		return fmt.Errorf("devicemapper: Can't get data size %s", err)
	}

	params := fmt.Sprintf("%s %s %d 32768 1 skip_block_zeroing", metadataFile.Name(), dataFile.Name(), poolBlockSize)
	if err := task.addTarget(0, size/512, "thin-pool", params); err != nil {
		return fmt.Errorf("devicemapper: Can't add target %s", err)
	}

	var cookie uint
	var flags uint16
	flags = DmUdevDisableSubsystemRulesFlag | DmUdevDisableDiskRulesFlag | DmUdevDisableOtherRulesFlag
	if err := task.setCookie(&cookie, flags); err != nil {
		return fmt.Errorf("devicemapper: Can't set cookie %s", err)
	}
	defer UdevWait(&cookie)

	if err := task.run(); err != nil {
		return fmt.Errorf("devicemapper: Error running deviceCreate (CreatePool) %s", err)
	}

	return nil
}
开发者ID:DaveDaCoda,项目名称:docker,代码行数:32,代码来源:devmapper.go

示例4: tree_cat_recursive

func tree_cat_recursive(files []os.FileInfo, dir *os.File) {

	for _, fileInfo := range files {

		if fileInfo.IsDir() {

			sourcedir := dir.Name() + "/" + fileInfo.Name()
			fmt.Println(sourcedir)

			new_dir, err := os.Open(sourcedir)
			checkerror(err)
			defer new_dir.Close()

			// Grab the files (list)
			new_files, err := new_dir.Readdir(0)
			checkerror(err)

			//() Recursive
			tree_cat_recursive(new_files, new_dir)

		} else {

			filename := dir.Name() + "/" + fileInfo.Name()
			//fmt.Println( filename , "\t", fileInfo.Size(), "\t", fileInfo.Mode(), fileInfo.ModTime() )
			fmt.Println(filename)

			//() cat the filecontent
			cat_file(filename)
		}
	}
}
开发者ID:ztgu,项目名称:tree-cat,代码行数:31,代码来源:tree-cat.go

示例5: load

func (v *Volume) load(alsoLoadIndex bool) error {
	var e error
	fileName := path.Join(v.dir, v.Id.String())
	if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists && !canRead {
		return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
	} else if !exists || canWrite {
		v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
	} else if exists && canRead {
		glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
		v.dataFile, e = os.Open(fileName + ".dat")
		v.readOnly = true
	} else {
		return fmt.Errorf("Unknown state about Volume Data file %s.dat", fileName)
	}
	if e != nil {
		if !os.IsPermission(e) {
			return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
		}
	}

	if v.ReplicaType == CopyNil {
		e = v.readSuperBlock()
	} else {
		e = v.maybeWriteSuperBlock()
	}
	if e == nil && alsoLoadIndex {
		var indexFile *os.File
		if v.readOnly {
			glog.V(1).Infoln("open to read file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
				return fmt.Errorf("cannot read Volume Data %s.dat: %s", fileName, e.Error())
			}

			if v.ensureConvertIdxToCdb(fileName) {
				v.nm, e = OpenCdbMap(fileName + ".cdb")
				return e
			}
			if indexFile != nil {
				glog.V(0).Infoln("converting %s.idx to %s.cdb", fileName, fileName)
				if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
					glog.Errorln("error converting %s.idx to %s.cdb: %s", fileName, fileName, e)
				} else {
					indexFile.Close()
					os.Remove(indexFile.Name())
					indexFile = nil
				}
			}
		} else {
			glog.V(1).Infoln("open to write file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
				return fmt.Errorf("cannot write Volume Data %s.dat: %s", fileName, e.Error())
			}
		}
		glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
		if v.nm, e = LoadNeedleMap(indexFile); e != nil {
			glog.V(0).Infoln("loading error:", e)
		}
	}
	return e
}
开发者ID:tgulacsi,项目名称:weed-fs,代码行数:60,代码来源:volume.go

示例6: Put

func (s *staticDB) Put(file *os.File, size int) error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if _, ok := s.assets[file.Name()]; ok {
		return fmt.Errorf("file already known, %q", file.Name())
	}

	buf := bytes.NewBuffer(nil)

	_, err := io.Copy(buf, file)
	if err != nil {
		return err
	}

	data := buf.Bytes()

	mimetype := mime.TypeByExtension(filepath.Ext(file.Name()))
	if mimetype == "" {
		log.Printf("[INFO] Couldn't detect mimetype from exntension, sniffing content: %q", file.Name())
		mimetype = http.DetectContentType(data)
	}
	log.Printf("[INFO] Mimetype of %q: %q", file.Name(), mimetype)

	h := md5.New()
	_, _ = h.Write(data)

	s.assets[file.Name()] = &asset{
		md5hex:   hex.EncodeToString(h.Sum(nil)),
		content:  data,
		mimetype: mimetype,
	}

	return nil
}
开发者ID:mokelab,项目名称:pkgname,代码行数:35,代码来源:static.go

示例7: startUpload

func (c *client) startUpload(id uint64, inPath string) (cancel func()) {
	killChan := make(chan bool, 1)
	go func() {
		var detachment *pond.Message_Detachment
		var tmp *os.File
		var err error
		if tmp, err = ioutil.TempFile("" /* default tmp dir */, "pond-upload-"); err != nil {
			err = errors.New("failed to create temp file: " + err.Error())
		} else {
			os.Remove(tmp.Name())
			defer tmp.Close()
			detachment, err = saveEncrypted(c.rand, c.backgroundChan, tmp, id, inPath, killChan)
			if err == nil {
				err = c.uploadDetachment(c.backgroundChan, tmp, id, killChan)
			}
		}
		if err == nil {
			detachment.Url = proto.String(c.buildDetachmentURL(id))
			c.log.Printf("Finished upload of %s", *detachment.Url)
			c.backgroundChan <- DetachmentComplete{id, detachment}
		} else {
			c.backgroundChan <- DetachmentError{id, err}
		}
		tmp.Close()
	}()
	return func() {
		killChan <- true
	}
}
开发者ID:radii,项目名称:pond,代码行数:29,代码来源:background.go

示例8: addFileToTar

func addFileToTar(fileWriter *os.File, tarWriter *tar.Writer, info os.FileInfo, relativePath, fullPath string) error {
	if relativePath == fileWriter.Name() || relativePath == "." || relativePath == ".." {
		return nil
	}

	if h, err := tar.FileInfoHeader(info, fullPath); err == nil {
		h.Name = relativePath
		if err := tarWriter.WriteHeader(h); err != nil {
			return err
		}
	}

	if info.IsDir() {
		return nil
	}

	li, err := os.Lstat(fullPath)
	if err != nil {
		return err
	}
	if li.Mode()&os.ModeSymlink == os.ModeSymlink {
		return nil
	}

	fr, err := os.Open(fullPath)
	if err != nil {
		return err
	}
	defer fr.Close()
	if _, err := io.Copy(tarWriter, fr); err != nil {
		return err
	}

	return nil
}
开发者ID:se77en,项目名称:lattice,代码行数:35,代码来源:droplet_runner_command_factory.go

示例9: NewSlowLogParser

func NewSlowLogParser(file *os.File, stopChan <-chan bool, opt Options) *SlowLogParser {
	// Seek to the offset, if any.
	// @todo error if start off > file size
	if opt.StartOffset > 0 {
		// @todo handle error
		file.Seek(int64(opt.StartOffset), os.SEEK_SET)
	}

	if opt.Debug {
		l.SetFlags(l.Ltime | l.Lmicroseconds)
		fmt.Println()
		l.Println("parsing " + file.Name())
	}

	p := &SlowLogParser{
		stopChan:    stopChan,
		opt:         opt,
		file:        file,
		EventChan:   make(chan *log.Event),
		inHeader:    false,
		inQuery:     false,
		headerLines: 0,
		queryLines:  0,
		bytesRead:   opt.StartOffset,
		lineOffset:  0,
		event:       log.NewEvent(),
	}
	return p
}
开发者ID:charity,项目名称:mysql-log-parser,代码行数:29,代码来源:slow.go

示例10: SendFile

func SendFile(file *os.File, fileLen int64) bool {
	var laddr = &net.TCPAddr{}
	var raddr = &net.TCPAddr{IP: Server.Nets[0].IP, Port: Server.Port}
	conn, err := net.DialTCP("tcp4", laddr, raddr)
	if err != nil {
		return false
	}
	conn.SetTimeout(2 * SECOND)
	defer conn.Close()

	pkt := make([]byte, MAX_TCP_PKT)
	if !responseServerAuth(conn, pkt) {
		return false
	}

	contentLen := int64(0)
	if fileLen%int64(Cipher.BlockSize()) == 0 {
		contentLen = fileLen
	} else {
		contentLen = (fileLen/int64(Cipher.BlockSize()) + 1) * int64(Cipher.BlockSize())
	}

	pktlen := 0
	pktlen += pktAddHeader(pkt[pktlen:], PACKET_TYPE_TAG, PACKET_TYPE_SEND_FILE)
	pktlen += pktAddHeader(pkt[pktlen:], USERNAME_TAG, Self.Name)
	pktlen += pktAddHeader(pkt[pktlen:], HOSTNAME_TAG, Self.Hostname)
	pktlen += pktAddHeader(pkt[pktlen:], FILE_NAME_TAG, filepath.Base(file.Name()))
	pktlen += pktAddHeader(pkt[pktlen:], CONTENT_LEN_TAG, strconv.Itoa64(contentLen))
	pktlen += pktAddHeader(pkt[pktlen:], PADDING_LEN_TAG, strconv.Itoa64(contentLen-fileLen))
	pktlen += pktAddHeaderEndMark(pkt[pktlen:])

	if writeBuf(conn, pkt[:pktlen]) != pktlen {
		return false
	}
	encrypter := NewCBCEncrypter()
	for {
		if fileLen < int64(cap(pkt)) {
			pkt = pkt[:fileLen]
		} else {
			pkt = pkt[:cap(pkt)]
		}
		if n, _ := fullRead(file, pkt); n != len(pkt) {
			return false
		}
		fileLen -= int64(len(pkt))
		if len(pkt)%Cipher.BlockSize() != 0 {
			//at file end
			n := (len(pkt)/Cipher.BlockSize() + 1) * Cipher.BlockSize()
			pkt = pkt[:n]
		}
		encrypter.CryptBlocks(pkt, pkt)
		if writeBuf(conn, pkt) != len(pkt) {
			return false
		}
		if fileLen <= 0 {
			break
		}
	}
	return true
}
开发者ID:zbq,项目名称:gg,代码行数:60,代码来源:gg.go

示例11: htmlOutput

// htmlOutput reads the profile data from profile and generates an HTML
// coverage report, writing it to outfile. If outfile is empty,
// it writes the report to a temporary file and opens it in a web browser.
func htmlOutput(profile, outfile string) error {
	profiles, err := ParseProfiles(profile)
	if err != nil {
		return err
	}

	var d templateData

	for _, profile := range profiles {
		fn := profile.FileName
		if profile.Mode == "set" {
			d.Set = true
		}
		file, err := findFile(fn)
		if err != nil {
			return err
		}
		src, err := ioutil.ReadFile(file)
		if err != nil {
			return fmt.Errorf("can't read %q: %v", fn, err)
		}
		var buf bytes.Buffer
		err = htmlGen(&buf, src, profile.Boundaries(src))
		if err != nil {
			return err
		}
		d.Files = append(d.Files, &templateFile{
			Name:     fn,
			Body:     template.HTML(buf.String()),
			Coverage: percentCovered(profile),
		})
	}

	var out *os.File
	if outfile == "" {
		var dir string
		dir, err = ioutil.TempDir("", "cover")
		if err != nil {
			return err
		}
		out, err = os.Create(filepath.Join(dir, "coverage.html"))
	} else {
		out, err = os.Create(outfile)
	}
	err = htmlTemplate.Execute(out, d)
	if err == nil {
		err = out.Close()
	}
	if err != nil {
		return err
	}

	if outfile == "" {
		if !browser.Open("file://" + out.Name()) {
			fmt.Fprintf(os.Stderr, "HTML output written to %s\n", out.Name())
		}
	}

	return nil
}
开发者ID:achanda,项目名称:go,代码行数:63,代码来源:html.go

示例12: setLogFile

func (r *Relay) setLogFile(logFile string) {
	r.status.Update("log-relay", "Setting log file: "+logFile)

	if logFile == "" {
		r.logger = nil
		r.logFile = ""
		r.status.Update("log-file", "")
		return
	}

	var file *os.File
	if logFile == "STDOUT" {
		file = os.Stdout
	} else if logFile == "STDERR" {
		file = os.Stderr
	} else {
		if !filepath.IsAbs(logFile) {
			logFile = filepath.Join(pct.Basedir.Path(), logFile)
		}
		var err error
		file, err = os.OpenFile(logFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
		if err != nil {
			r.internal(err.Error())
			return
		}
	}
	logger := golog.New(file, "", golog.Ldate|golog.Ltime|golog.Lmicroseconds)
	r.logger = logger
	r.logFile = file.Name()
	r.status.Update("log-file", logFile)
}
开发者ID:huangzhiyong,项目名称:percona-agent,代码行数:31,代码来源:relay.go

示例13: saveAttachment

func saveAttachment(contact contactInfo, attachment io.Reader, name string, msg *textsecure.Message) (err error) {
	var output *os.File

	attachmentPath := contact.AttachmentDir

	err = os.MkdirAll(attachmentPath, 0700)

	if err != nil {
		return
	}

	if name == "" {
		output, err = ioutil.TempFile(attachmentPath, "attachment_")
	} else {
		outputPath := filepath.Join(attachmentPath, name)
		output, err = os.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL|os.O_TRUNC, 0600)
	}

	if err != nil {
		return
	}
	defer output.Close()

	io.Copy(output, attachment)
	status.Log(syslog.LOG_NOTICE, "saved attachment from %s %s\n", contact.Name, contact.Number)

	name = relativePath(output.Name())
	updateHistory(contact, "["+name+"]", "<", msg.Timestamp())

	return
}
开发者ID:jmptrader,项目名称:interlock,代码行数:31,代码来源:textsecure.go

示例14: convertDmndToBlastTabular

func convertDmndToBlastTabular(daa *os.File) (*os.File, error) {
	dmndOutFile, err := ioutil.TempFile(".", "dmnd-out-tab-")
	if err != nil {
		return nil, fmt.Errorf("Could not build temporary file for diamond output: %s", err)
	}

	cmd := exec.Command(
		flagDmnd,
		"view",
		"-o", dmndOutFile.Name(),
		"-a", daa.Name())

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout

	err = mica.Exec(cmd)
	if err != nil {
		return nil, fmt.Errorf("Error converting daa file to blast tabular: %s", err)
	}
	// err = os.Remove(daa.Name())
	// if err != nil {
	// 	return nil, fmt.Errorf("Error destroying .daa file: %s", err)
	// }
	return dmndOutFile, nil
}
开发者ID:jameslz,项目名称:MICA,代码行数:25,代码来源:diamond.go

示例15: extractM4A

func extractM4A(file *os.File, offset string, duration string, output string) error {
	path, err := exec.LookPath("ffmpeg")
	if err != nil {
		return err
	}

	if offset == "" {
		offset = "0"
	}

	args := []string{"-ss", offset}

	if duration != "" {
		args = append(args, "-t", duration)
	}

	args = append(args, "-i", file.Name(), "-vn", "-y", "-acodec", "copy", output)

	cmd := exec.Command(path, args...)
	log.Println(cmd.Args)

	err = cmd.Run()
	if err != nil {
		return err
	}

	return nil
}
开发者ID:Jirai,项目名称:gohn,代码行数:28,代码来源:rpc.go


注:本文中的os.File.Name方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。