Java读取txt文件和写入txt文件

ackage edu.thu.keyword.test; import java.io.File; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; public class cin_txt { static void main(String args[]) { try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw /* 读入TXT文件 */ String pathname = "D:\\twitter\\13_9_6\\dataset\\en\\input.txt"; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径 File filename = new File(pathname); // 要读取以上路径的input。txt文件 InputStreamReader reader = new InputStreamReader( new FileInputStream(filename)); // 建立一个输入流对象reader BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言 String line = ""; line = br.readLine(); while (line != null) { line = br.readLine(); // 一次读入一行数据 } /* 写入Txt文件 */ File writename = new File(".\\result\\en\\output.txt"); // 相对路径,如果没有则要建立一个新的output。txt文件 writename.createNewFile(); // 创建新文件 BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write("我会写入文件啦\r\n"); // \r\n即为换行 out.flush(); // 把缓存区内容压入文件 out.close(); // 最后记得关闭文件 } catch (Exception e) { e.printStackTrace(); } } }


java读取txt文件内容。可以作如下理解:

1、首先获得一个文件句柄。File file = new File(); file即为文件句柄。两人之间连通电话网络了。接下来可以开始打电话了。

2、通过这条线路读取甲方的信息:new FileInputStream(file) 目前这个信息已经读进来内存当中了。接下来需要解读成乙方可以理解的东西

3、既然你使用了FileInputStream()。那么对应的需要使用InputStreamReader()这个方法进行解读刚才装进来内存当中的数据

4、解读完成后要输出呀。那当然要转换成IO可以识别的数据呀。那就需要调用字节码读取的方法BufferedReader()。同时使用bufferedReader()的readline()方法读取txt文件中的每一行数据哈。

方法一:
简单的使用Scanner和PrintWriter
[java]  view plain  copy
  1. package com.stone.demo;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.PrintWriter;  
  6. import java.util.Scanner;  
  7.   
  8. public class ReadAndWriteTxtByScanner {  
  9.   
  10.     private static void readTxtFile(String filepath){  
  11.         try {  
  12.             Scanner in=new Scanner(new File(filepath));  
  13.             while(in.hasNext()){  
  14.                 String str=in.nextLine();  
  15.                 System.out.println(str);  
  16.             }  
  17.         } catch (FileNotFoundException e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  
  21.       
  22.     private static void writeTxtFile(String filepath){  
  23.         try {  
  24.             @SuppressWarnings("resource")  
  25.             String relativepath=System.getProperty("user.dir")+"/src/com/stone/demo/writefile.txt";  
  26.             PrintWriter out=new PrintWriter(relativepath);  
  27.             out.write("12312");  
  28.             out.write("\n");  
  29.             out.write("12312");  
  30.             out.flush();  
  31.             out.close();  
  32.         } catch (Exception e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.     }  
  36.       
  37.     public static void main(String[] args) {  
  38.         String filepath=System.getProperty("user.dir")+"/src/com/stone/demo/writefile.txt";  
  39.         writeTxtFile(filepath);  
  40.         System.out.println("==================");  
  41.         readTxtFile(filepath);  
  42.     }  
  43. }  

方法二:使用IO流
[java]  view plain  copy
  1. package com.stone.demo;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.FileWriter;  
  9. import java.io.IOException;  
  10. import java.io.InputStreamReader;  
  11. import java.util.Scanner;  
  12.   
  13. public class ReadAndWriteTxtByFile {  
  14.     /** 
  15.      * 功能:Java读取txt文件的内容 步骤: 
  16.      * 1:先获得文件句柄  
  17.      * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取 
  18.      * 3:读取到输入流后,需要读取生成字节流 
  19.      *  4:一行一行的输出。readline()。 备注:需要考虑的是异常情况 
  20.      * @param filePath 
  21.      */  
  22.     public static void readTxtFile(String filePath) {  
  23.         try {  
  24.             String encoding = "GBK";  
  25.             File file = new File(filePath);  
  26.             if (file.isFile() && file.exists()) { // 判断文件是否存在  
  27.                 InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式  
  28.                 BufferedReader bufferedReader = new BufferedReader(read);  
  29.                 String lineTxt = null;  
  30.                 while ((lineTxt = bufferedReader.readLine()) != null) {  
  31.                     System.out.println(lineTxt);  
  32.                 }  
  33.                 read.close();  
  34.             }  
  35.         } catch (Exception e) {  
  36.             System.out.println("读取文件内容出错");  
  37.             e.printStackTrace();  
  38.         }  
  39.     }  
  40.       
  41.     private static void writeTxtFile(String filepath){  
  42.         File file=new File(filepath);  
  43.         BufferedWriter writer = null;  
  44.         try {  
  45.             if(file.isFile()&&!file.exists()){  
  46.                 System.out.println("找不到指定的文件");  
  47.                 file.createNewFile();// 不存在则创建  
  48.             }  
  49.             else{  
  50.                 //writer = new BufferedWriter(new FileWriter(file,true)); //这里加入true 可以不覆盖原有TXT文件内容 续写  
  51.                 writer = new BufferedWriter(new FileWriter(file));  
  52.                 writer.write("hello");  
  53.                 writer.write("\n");  
  54.                 writer.write("hello");  
  55.             }  
  56.               
  57.         } catch (Exception e) {  
  58.             e.printStackTrace();  
  59.         } finally {  
  60.             if (writer != null) {  
  61.                 try {  
  62.                     writer.flush();  
  63.                     writer.close();  
  64.                 } catch (IOException e) {  
  65.                     e.printStackTrace();  
  66.                 }  
  67.             }  
  68.         }  
  69.     }  
  70.       
  71.     public static void main(String argv[]) {  
  72.         String filepath=System.getProperty("user.dir")+"/src/com/stone/demo/txtfile.txt";  
  73.         writeTxtFile(filepath);  
  74.         System.out.println("===================");  
  75.         readTxtFile(filepath);  
  76.     }  
  77. }  
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个txt文件中的数据写入数据库,你需要完成以下步骤: 1. 创建数据库连接:使用DriverManager类的getConnection()方法创建一个数据库连接。此方法需要数据库的URL、用户名和密码等参数。 2. 打开txt文件:使用Java I/O操作打开txt文件,并读取其中的数据。 3. 将数据插入到数据库:使用PreparedStatement对象将读取的数据插入到数据库中。在插入数据之前,你需要为PreparedStatement对象设置SQL语句中的占位符(使用问号表示)并设置对应的参数。 4. 关闭连接:在完成所有操作之后,记得关闭数据库连接。 下面是一个简单的Java程序,演示了如何将txt文件中的数据写入MySQL数据库: ```java import java.io.BufferedReader; import java.io.FileReader; import java.sql.*; public class Main { public static void main(String[] args) { try { // 加载MySQL JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 创建数据库连接 Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydatabase", "username", "password"); // 打开txt文件 BufferedReader br = new BufferedReader(new FileReader("data.txt")); // 创建插入数据的PreparedStatement对象 String sql = "INSERT INTO mytable(name, age) VALUES(?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); // 逐行读取txt文件并插入到数据库中 String line; while ((line = br.readLine()) != null) { String[] parts = line.split(","); String name = parts[0]; int age = Integer.parseInt(parts[1]); pstmt.setString(1, name); pstmt.setInt(2, age); pstmt.executeUpdate(); } // 关闭连接 pstmt.close(); conn.close(); br.close(); } catch (Exception ex) { ex.printStackTrace(); } } } ``` 在上面的代码中,你需要将数据库URL、用户名和密码替换为你自己的信息。此外,你需要将data.txt文件放在程序所在的目录下,并按照逗号分隔每一行的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值