`

java IO输入输出流的操作-文件、txt、xml

阅读更多
1、读取目录下指定后缀的文件
public  List<String> readFile(String dirPath) {
       // 建立当前目录中文件的File对象
   		File file = new File(dirPath);
       // 取得代表目录中所有文件的File对象数组
   		File[] list = file.listFiles();
       // 遍历file数组
   		for (int i = 0; i < list.length; i++) {
   			if(list[i].isDirectory()) { 
                   	readFile(list[i].getPath());//递归
             }
   			else{
   				if(list[i].getName().endsWith("htm")){
   					dirPath1.add(list[i].getPath());
   		         }
   			}
   		}
	return dirPath1;
}

2、一行一行的读取文本内容
public  String Reader() throws IOException{
		String temp=null;
		File file=new File("C:\\Users\\Administrator\\Desktop\\tests");
		File[] list=file.listFiles();
		for(int i=0;i<list.length;i++){
                StringBuffer content=new StringBuffer();
                InputStreamReader isr=new InputStreamReader(new                   FileInputStream(list[i].getAbsolutePath()));
                BufferedReader read=new BufferedReader(isr);
	            while((temp=read.readLine())!=null){
				content.append(temp);
				content.append("\n");
				}
		}
		return content.toString();
	}

3、将整个内容写到文本
 public static void FileWrite(String fileName, String content) {   
        FileWriter writer = null;  
        try {     
            // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件     
            writer = new FileWriter(fileName, true);    
            writer = new FileWriter(fileName);//不追加文件内容
            writer.write(content);       
        } catch (IOException e) {     
            e.printStackTrace();     
        } finally {     
            try {     
                if(writer != null){  
                    writer.close();     
                }  
            } catch (IOException e) {     
                e.printStackTrace();     
            }     
        }   
    }

4、将字符串内容循环写到文本中  
public String WriteTopic(ArrayList result) throws FileNotFoundException{
		Book book=new Book();
		String id=null;
		String body=null;
		String document=null;
		String qrel=null;
		for(int i=0;i<result.size();i++){
			Pattern p0=Pattern.compile("id=(.*?)bioasq");
			Matcher m0=p0.matcher(result.get(i).toString());
			while(m0.find()){
				id=m0.group(1);
				book.setId(id);
			}
			Pattern p1=Pattern.compile("body:\"(.*?)\"");
			Matcher m1=p1.matcher(result.get(i).toString());
			while(m1.find()){
				body=m1.group(1);
				book.setBody(body);
			}
			Pattern p2=Pattern.compile("\"http://www.ncbi.nlm.nih.gov/pubmed/(.*?)\"");
			Matcher m2=p2.matcher(result.get(i).toString());
			while(m2.find()){
				document=m2.group(1);
	//			book.setDocument(document);
				qrel=id+" "+"0"+" "+document+" "+"1";
				System.out.println(qrel);
				FileOutputStream fos=new FileOutputStream("C:\\Users\\Administrator\\Desktop\\BioASQ_2013_TaskB\\BioASQ_PhaseB.qrel",true);
				PrintStream ps=new PrintStream(fos);
				Scanner in=new Scanner(qrel);
				String s=in.next();
				System.setOut(ps);
		//		System.out.println(s);
			}
		}
		return qrel;
	}

BioASQ_PhaseB.qrel格式
1 0 23220349 1
1 0 19582169 1
1 0 22161322 1
1 0 18025684 1
1 0 15701682 1
1 0 15215406 1
1 0 18081932 1
1 0 18629289 1
1 0 21729286 1
1 0 11438739 1
1 0 10573422 1
2 0 22975810 1
2 0 22852678 1
2 0 22278059 1
2 0 21500720 1
2 0 23331310 1
2 0 23250067 1
2 0 23003992 1
2 0 22714377 1
2 0 22665786 1
2 0 22653729 1
2 0 22330507 1
2 0 22286383 1
2 0 21293374 1
3 0 22921312 1
3 0 22480152 1
3 0 22315491 1
3 0 22258533 1
3 0 21415082 1
3 0 21068339 1
3 0 20569258 1
4 0 23297037 1
4 0 22987359 1
4 0 22540951 1
4 0 22247276 1
......

5、写xml
public void getTopics(String title,String narrative) throws IOException{
		Document document=DocumentHelper.createDocument();
		OutputFormat format=OutputFormat.createPrettyPrint();
		Element root=document.addElement("parameters");
		Element topic=root.addElement("topic");
	   topic.setAttributeValue("id", "1");
	//	topic.setAttributeValue("id",1 );
		Element titleElement=topic.addElement("title");
		Element groupElement=topic.addElement("group");
		Element narrativeElement=topic.addElement("narrative");
		if(title!=null){
		titleElement.setText(title);
		}
		if(narrative!=null){
			narrativeElement.setText(narrative);
		}
		/*File file=new File("/home/zzj/test.topics");
		file.mkdirs();*/
		XMLWriter writer=new XMLWriter(new FileWriter(new File("/home/douban/test.xml")),format);
		writer.write(document);
		writer.flush();
		writer.close();
		
	}

test.xml格式
<?xml version="1.0" encoding="UTF-8"?>

<parameters>
  <topic id="1">
    <title>Give examples of next-generation sequencing applications in mutation screening?</title>
    <group/>
    <narrative>Give examples of next-generation sequencing applications in mutation screening?</narrative>
  </topic>
</parameters>

6、写XML文件,如何在同一个节点下循环加入多个节点
public void WrtierTopics(ArrayList result) throws IOException {
		String body=null;
		Document doc=DocumentHelper.createDocument();
		OutputFormat format=OutputFormat.createPrettyPrint();
		Element root=doc.addElement("parameters");
		for(int i=0;i<result.size();i++){
			Pattern p0=Pattern.compile("id=(.*?)bioasq");
			Matcher m0=p0.matcher(result.get(i).toString());
			Pattern p1=Pattern.compile("body:\"(.*?)\"");
			Matcher m1=p1.matcher(result.get(i).toString());
			if(m1.find()){
				body=m1.group(1);
			}
			Element topic=root.addElement("topic");
			topic.setAttributeValue("id", "1");//topic中的id值固定为1
			Element titleElement=topic.addElement("title");
			Element groupElement=topic.addElement("group");
			Element narrativeElement=topic.addElement("narrative");
			titleElement.setText(body);
			narrativeElement.setText(body);
		}
		XMLWriter writer=new XMLWriter(new FileWriter(new File("C:\\Users\\Administrator\\Desktop\\BioASQ_2013_TaskB\\BioASQ_phaseB.topic")),format);	
		writer.write(doc);
		writer.flush();
		writer.close();
	}

BioASQ_PhaseB.topic格式:
<?xml version="1.0" encoding="UTF-8"?>

<parameters>
  <topic id="1">
    <title>How could we infer functional associations from gene fusion events?</title>
    <group/>
    <narrative>How could we infer functional associations from gene fusion events?</narrative>
  </topic>
  <topic id="1">
    <title>Where is X-ray free electron laser used?</title>
    <group/>
    <narrative>Where is X-ray free electron laser used?</narrative>
  </topic>
  <topic id="1">
    <title>Give examples of next-generation sequencing applications in mutation screening?</title>
    <group/>
    <narrative>Give examples of next-generation sequencing applications in mutation screening?</narrative>
  </topic>
  <topic id="1">
    <title>What are the computational methods for the prediction of beta-barrel transmembrane proteins?</title>
    <group/>
    <narrative>What are the computational methods for the prediction of beta-barrel transmembrane proteins?</narrative>
  </topic>
......
</parameters>
分享到:
评论

相关推荐

    IO流、Xml解析

    IO流还包括输入流(Input Stream)、输出流(Output Stream)、缓冲流(Buffered Stream)、转换流(Converter Stream)以及对象流(Object Stream)等子类,它们各自有不同的功能和应用场景。例如,FileInputStream...

    java+servlet+commons-io-2.4.jar+commons-fileupload-1.3.jar实现文件的上传与下载

    3. **读取文件**:使用Commons IO库读取文件内容,将其写入到响应的输出流中。 4. **关闭流**:确保所有的流都被正确关闭,避免资源泄漏。 五、代码示例 ```java // 文件上传 public class UploadServlet extends ...

    Java考试前总结(包含io输入输出流/线程/特殊for语句/文件读写的总结)

    总结来说,理解和掌握Java的I/O流可以帮助你有效地处理数据输入输出,线程管理则让你能够编写并发程序,特殊for语句简化了代码,而文件读写则是日常开发的基本技能。这些知识点的掌握程度直接影响到你在Java考试中的...

    Java IO 字节流 字符流

    对于工具的使用,开发者经常使用如Apache Commons IO库中的工具类,如FileUtils、IOUtils等,它们提供了许多方便的静态方法,简化了常见的IO操作,比如复制文件、读取文件内容等。同时,Java 7引入的try-with-...

    java读取跟输出xml文件

    2. 读取XML文档:利用`SAXBuilder`,可以从文件或输入流中读取XML文档并将其转换为`Document`对象。这允许你遍历文档的节点,提取数据或进行其他操作。 接下来,XStream是另一个强大的工具,它允许将Java对象直接...

    java io流 xml 泛型 例子学习

    IO流在Java中是用来处理输入输出操作的核心机制。它允许程序与外部设备(如硬盘、键盘、网络等)进行数据交换。Java IO流分为字节流和字符流,又有输入流和输出流之分。字节流处理单个字节的数据,而字符流处理...

    java io流学习笔记1

    Java IO流是Java编程语言中处理输入输出操作的重要部分,尤其在数据传输、文件读写等方面发挥着核心作用。本文将深入探讨Java IO流的基本概念、类型以及它们在实际开发中的应用。 首先,理解IO流的基本概念至关重要...

    Java IO 编程集合

    总的来说,Java IO编程集合涵盖了从基础的文件操作到复杂的流处理,通过实例学习,可以更好地理解和掌握Java在处理文件输入输出方面的强大功能。在实践中,我们需要根据具体需求选择合适的IO类,合理地组织代码,...

    commons-io-2.2

    在版本2.2中,这个库提供了一系列精心设计和优化的类和方法,极大地简化了与输入/输出流、文件系统、字符集、线程相关的复杂任务。本文将深入探讨Apache Commons IO 2.2中的关键知识点,以及如何在实际项目中有效地...

    java读写Xml文件(UTF-8) 【一】

    - **加载文件**: 使用`DocumentBuilder`的`parse()`方法,传入XML文件的输入流或路径,加载XML文档到内存中。 - **获取根元素**: 解析后的XML文档是一个`Document`对象,我们可以调用`getDocumentElement()`方法...

    JAVA对象序列化保存为XML文件的工具类

    `XMLEncoder`是一个用于将Java对象编码为XML输出流的类,它能够将对象的属性和结构转换为XML格式。而`XMLDecoder`则相反,它可以解析XML输入流并重建原始的Java对象。这两个工具使得在XML和Java对象之间进行序列化和...

    hadoop 2.9.0 mapred-default.xml 属性集

    配置Map任务在进行排序操作时,单个溢写(Spill)操作可以使用的最大输出流数。 9. mapreduce.task.io.sort.mb 配置Map任务的排序缓冲区大小(以MB为单位)。 10. mapreduce.map.sort.spill.percent 配置Map任务...

    Java IO流:从xml文件中读取数据,在程序中创建对象

    在Java编程中,IO流(Input/Output Stream)是一个核心概念,用于处理数据的输入与输出。本主题将深入探讨如何使用Java IO流从XML文件中读取数据,并在程序中根据这些数据创建对象。XML(Extensible Markup Language...

    使用JAVA.IO流线程的JAVA课设项目万年历记事本

    - **输入流**(InputStream)用于读取数据,而**输出流**(OutputStream)用于写入数据。这个项目可能使用了FileInputStream和FileOutputStream进行文件操作。 - **字符流**(Reader和Writer)处理文本数据,而**...

    commons-io-2.6.jar

    1. 输入/输出流:`IOUtils`类提供了对输入/输出流的读写操作,如`readFully()`和`write()`,以及关闭流的便捷方法`closeQuietly()`,防止因异常导致的资源泄露。 2. 转换流:`CharSequenceInputStream`和`...

    commons-io-2.4

    这个库包含了大量方便、高效的类和方法,帮助开发者处理输入/输出流、文件、字符集、序列化等问题,极大地简化了日常的IO编程工作。 在"commons-io-2.4"这个压缩包中,你可以找到以下组件: 1. **commons-io-2.4-...

    android 文件操作 输入流对象 输出流对象 SDCard读写

    这里主要关注的是如何使用输入流对象(InputStream)和输出流对象(OutputStream)进行SDCard(外部存储卡)的读写操作。下面将详细介绍这些概念和实践中的应用。 1. **Android 文件操作**: Android 提供了丰富的...

    自己写的java对xml文件操作的类

    为了提高代码的可维护性和复用性,你可能还实现了异常处理、输入/输出流的管理,以及一些辅助方法,如检查文件是否存在、确保文件可读可写等。此外,考虑到性能,你可能考虑过使用SAX或StAX进行更高效的XML处理,...

    622.620.JAVA基础教程_IO流与网络编程-端口号的理解(622).rar

    2. 字符流:Reader和Writer是所有字符输入流和输出流的基类,它们处理文本数据,如文本文件、XML文档等。 3. 流的方向性:输入流用于从源读取数据,输出流用于向目的地写入数据。 4. 转换流:InputStreamReader和...

    626.624.JAVA基础教程_IO流与网络编程-TCP网络编程例题3(626).rar

    - 一旦连接建立,双方可以通过`Socket`对象的`getInputStream()`和`getOutputStream()`方法获取输入流和输出流,进行数据的读写。 - 数据通常以字节流的形式传输,可以使用`InputStream`和`OutputStream`的子类,...

Global site tag (gtag.js) - Google Analytics