public class FileUtils { private static final String ENCODING = "UTF-8";//编码方式 /**
* 获取文件的行
*
* @param fileName
* 文件名称
* @return List<String>
*/
public static String getContentByLine(String fileName) {
StringBuffer lines = new StringBuffer();
InputStreamReader read = null;
BufferedReader bufferedReader = null;
try {
String configPath = FileUtils.class.getClassLoader().getResource(fileName).getPath();
configPath = configPath.replaceAll("%20", " ");// 处理文件路径中空格问题
File file = new File(configPath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
read = new InputStreamReader(new FileInputStream(file), ENCODING);
bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
if (lineTxt == null || lineTxt.length() == 0) {
continue;
}
lines.append(lineTxt);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (read != null) {
read.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return lines.toString();
}
}
相关文章
- Java操作文件夹的工具类
- 文件相关操作工具类——FileUtils.java
- Android 读取Json文件的工具类
- java实现读取excel或者txt文件,导入MongoDB数据库
- 方法:一个简单的读取配置文件.properties的工具类 JAVA
- Winform主菜单两种实现方式-1.)从工具箱中双击MenuStrip控件,窗体的顶部就会放置一个MenuStrip控件,或者在工具箱中单击MenuStrip控件,拖至窗体中也可以. 2.)在MenuStrip的“Type Here”输入主菜单和菜单名字,热键用(&X)表示. 用快捷键选择主菜单,可以用Alt + 预定义的按键来实现,子菜单的选择只需要按定义的热键即可. 3.)双击File*菜单下面的子菜单,创建子菜单Open、Save、Exit的单击事件代码: private void OpenOToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog { //初始化打开对话框的路径 InitialDirectory = @"D:\", Title = "Open File", //定义可显示的文件类型; Filter = "txt file(*.txt)|*.txt|All file(*.*)|*.*", //定义默认显示的文件类型为txt FilterIndex = 1, //对话框关闭后将复位初始化路径 RestoreDirectory = true }; if (ofd.ShowDialog == DialogResult.OK) { //根据打开对话框选择的文件名,加载文本内容到富文本框中. richtxtContent.Text = File.ReadAllText(ofd.FileName); } } private void SaveSToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog { //初始化保存对话框的路径 InitialDirectory = @"D:\", Title = "Save File", //定义可显示的文件类型; Filter = "txt file(*.txt)|*.txt|All file(*.*)|*.*", //定义默认显示的文件类型为txt FilterIndex = 1, //对话框关闭后将复位初始化路径 RestoreDirectory = true }; if(sfd.ShowDialog == DialogResult.OK) { //保存文件 File.WriteAllText(sfd.FileName, richtxtContent.Text); //清空富文本框内容 richtxtContent.Clear; } } private void exitEToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit; } 4.)执行下程序,加载指定的txt文件到富文本框中,如下: 5.)在富文本框中更新加载进来的txt文件内容. 6.)Alt + F热键打开文件的下拉菜单,单击S保存富文本框中的内容到指定的文件.打开txt验证菜单单击事件保存文件成功. 二.实现winform主菜单的方法2:MenuStrip类和toolStripMenuItem类实例化对象,在主窗体加载事件中实现如下代码:
- 关于JAVA中File类中listFiles读取指定后缀的所有文件中关于指定盘符路径碰到的问题**
- Java读取txt文件和覆盖写入txt文件和追加写入txt
- File类的特点?如何创建File类对象?Java中如何操作文件内容,什么是Io流Io流如何读取和写入文件?字节缓冲流使用原则?
- 创建普通properties工具类读取spring boot的application.properties文件中的属性