在java中怎样让用户输入文件名来打开一个文件?

在java中怎样让用户输入文件名来打开一个文件?,第1张

import java.io.BufferedReader

import java.io.FileReader

import java.io.IOException

import java.util.Scanner

public class Test{

public static void main(String[] args) throws IOException {

Scanner sc = new Scanner(System.in)

System.out.println("请输入文件名:")

String fileName = sc.nextLine()

BufferedReader br = new BufferedReader(new FileReader(fileName))

String line

while((line = br.readLine()) != null){

System.out.println(line)

}

br.close()

sc.close()

}

}

输入:e:/1.txt

就会打开e盘下的1.txt了

基本上面几位都说啦。。。

只说一点就是注意null和空的处理

import java.io.File

import java.util.HashSet

import java.util.Set

public class ReadFileSample {

private static final String PATH = "C:\\TEST"

private static final char SEPARATOR = '_'

public static void main(String[] args) {

Set<String>fileSet = new HashSet<String>()

File[] files = new File(PATH).listFiles()

for (File file : files) {

// 由于Set的元素是不重复的,不用做重复判断,直接放入

fileSet.add(getPrefixFileName(file.getName()))

}

// 由于Set允许null,所以要去除

fileSet.remove(null)

// 打印出Set的内容(需要的数据)

System.out.println(fileSet)

}

private static String getPrefixFileName(String fileName) {

if (fileName == null || fileName.length() == 0) {

return null

}

int index = fileName.indexOf(SEPARATOR)

if (index <0) {

// 不含SEPARATOR的文件名

return null

}

// 从文件名开头到SEPARATOR的位置,截取

return fileName.substring(0, index)

}

}

找JAVA *** 作IO的章节,其实是流(字符与字节)的实现上,发个参考给你

public static String getFileText(String path,String filename,FileEnum enums) throws IOException {

FileInputStream inputstream = null

try{

inputstream = new FileInputStream(path+ File.separator + filename)

switch(enums){

case jpg:

return encodeImgageToBase64(inputstream,FileEnum.getFileTypeEnum(FileEnum.jpg).toString())

case doc:

return readWordFileToStr(inputstream)

case text:

returnreadTextFileToStr(inputstream)

default :

return ""

}

}catch(IOException e){

throw e

}finally{

closeStream(inputstream)

}

}

private static String readTextFileToStr(FileInputStream inputstream) throws IOException {

String result = ""

InputStreamReader read = new InputStreamReader(inputstream)

BufferedReader bufferedReader = new BufferedReader(read)

String lineTxt = null

while((lineTxt = bufferedReader.readLine()) != null){

result = result + "\n" +lineTxt

}

return result

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12100752.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存