java将对象保存到文件中从文件中读取对象
- 格式:docx
- 大小:23.98 KB
- 文档页数:3
java程序读取服务器端数据文件的方法
1. 使用Java IO流读取服务器端文件:
使用Java IO流可以读取服务器端文件,具体步骤如下:
(1)使用URL类的openStream()方法获取URL对象的输入流;
(2)使用BufferedReader类的readLine()方法读取文件内容;
(3)使用String类的split()方法将读取的内容按照指定的分隔符分割为字符串数组;
(4)使用Arrays类的toString()方法将字符串数组转换为字符串;
(5)使用String类的replace()方法替换掉特殊字符;
(6)使用String类的split()方法将字符串按照指定的分隔符分割为字符串数组;
(7)使用for循环遍历字符串数组,将每个字符串元素添加到ArrayList中;
(8)将ArrayList转换为字符串数组,并返回。
2. 使用Java NIO读取服务器端文件:
使用Java NIO可以读取服务器端文件,具体步骤如下:
(1)使用Paths类的get()方法获取服务器端文件的路径;
(2)使用Files类的readAllBytes()方法读取文件的所有字节;
(3)使用String类的split()方法将读取的内容按照指定的分隔符分割为字符串数组;
(4)使用for循环遍历字符串数组,将每个字符串元素添加到ArrayList中;
(5)将ArrayList转换为字符串数组,并返回。
Java语言程序设计第六章课后习题答案1.将本章例6-1至6-18中出现的文件的构造方法均改为使用File类对象作为参数实现。
个人理解:File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。
注意:是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。
import java.io.*;public class test6_2{public static void main(String[] args) throws IOException { String fileName = "D:\\Hello.txt";File writer=new File(fileName);writer.createNewFile();BufferedWriter input = new BufferedWriter(newFileWriter(writer));input.write("Hello !\n");input.write("this is my first text file,\n");input.write("你还好吗?\n");input.close();}}运行结果:(电脑系统问题,没法换行,所以一般使用BuffereWriter中newLine()实现换行)2.模仿文本文件复制的例题,编写对二进制文件进行复制的程序.// CopyMaker类import java.io.*;class CopyMaker {String sourceName, destName;BufferedInputStream source;BufferedOutputStream dest;int line;//打开源文件和目标文件,无异常返回trueprivate boolean openFiles() {try {source = new BufferedInputStream(newFileInputStream( sourceName ));}catch ( IOException iox ) {System.out.println("Problem opening " + sourceName );return false;}try {dest = new BufferedOutputStream(newFileOutputStream( destName ));}catch ( IOException iox ){System.out.println("Problem opening " + destName );return false;}return true;}//复制文件private boolean copyFiles() {try {line = source.read();while ( line != -1 ) {dest.write(line);line = source.read();}}catch ( IOException iox ) {System.out.println("Problem reading or writing" );return false;}return true;}//关闭源文件和目标文件private boolean closeFiles() {boolean retVal=true;try { source.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + sourceName );retVal = false;}try { dest.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + destName );retVal = false;}return retVal;}//执行复制public boolean copy(String src, String dst ) {sourceName = src ;destName = dst ;return openFiles() && copyFiles() && closeFiles();}}//test6_2public class test6_2{public static void main ( String[] args ) {String s1="lin.txt",s2="newlin.txt";if(new CopyMaker().copy(s1, s2))S ystem.out.print("复制成功");elseS ystem.out.print("复制失败");}}运行前的两个文本:lin.txt和newlin.txt(为空)运行后:3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。
一、概述Java是一种流行的编程语言,广泛应用于企业级软件开发。
在Java应用程序中,经常需要读取配置文件中的参数,以便程序在不同环境下能够灵活运行。
本文将介绍在Java中获取配置文件参数的方法。
二、使用Properties类在Java中,可以使用Properties类来读取配置文件。
Properties是HashTable的子类,它用于处理键值对形式的配置信息。
下面是使用Properties类获取配置文件参数的步骤:1. 创建Properties对象首先使用Properties类创建一个对象,用于存储配置文件中的参数。
可以通过以下代码实现:```javaProperties props = new Properties();```2. 加载配置文件接下来,需要将配置文件加载到Properties对象中。
通常配置文件的格式是.properties,可以通过以下代码加载:```javatry{InputStream inputStream =getClass().getClassLoader().getResourceAsStream("config.prope rties");props.load(inputStream);}catch(IOException e){e.printStackTrace();}```上述代码中,使用ClassLoader的getResourceAsStream方法加载配置文件,并使用Properties的load方法将文件内容加载到props 对象中。
3. 获取参数值一旦配置文件加载到props对象中,就可以通过getProperty方法获取参数值。
获取名为"db.url"的参数值可以使用以下代码:```javaString dbUrl = props.getProperty("db.url");```通过上述步骤,就可以在Java中轻松获取配置文件中的参数值了。
java中writeobject的用法Java中的writeObject()是一个序列化方法,它用于将Java对象转化为二进制形式以便存储到文件中或通过网络传输。
这个方法是Java中的一个重要功能,它可以让我们将一个序列化对象写入到输出流中,并将其保存到磁盘上或者发送到另一个程序。
下面,我们将更详细地介绍Java中writeObject()的用法。
1.创建一个实现了Serializable接口的类在Java中,如果想要使用writeObject()方法,我们需要创建一个实现了Serializable接口的类。
这是因为Serializable接口标记了一个类可以被序列化,表明它的内部状态可以被存储到磁盘或者通过网络传输。
例如,我们可以创建一个名为Person的类,并让它实现Serializable接口:public class Person implements Serializable {private String name;private int age;public Person(String name, int age) { = name;this.age = age;}//省略getter和setter方法}2.使用ObjectOutputStream类将对象写入文件中一旦一个Serializable类被创建,我们就可以使用writeObject()方法将实例对象写入到文件中。
我们需要使用Java的ObjectOutputStream类来将对象写入到输出流中。
ObjectOutputStream类包含了许多方法,它们可以用于序列化和写入各种不同类型的Java对象。
下面是一个例子:try {FileOutputStream fileOut = newFileOutputStream("person.ser");ObjectOutputStream out = new ObjectOutputStream(fileOut); Person person = new Person("Tom", 28);out.writeObject(person);out.close();fileOut.close();} catch (IOException i) {i.printStackTrace();}在这个例子中,我们创建了一个Person类的实例对象,并使用ObjectOutputStream的writeObject()方法将其写入到person.ser文件中。
如何在Java中进行数据的持久化和读取操作数据的持久化是指将程序中的数据存储在持久存储介质中(如文件、数据库等)以便下次程序运行时能够重新读取和使用。
在Java中,数据的持久化和读取操作可以通过文件操作、数据库操作、序列化和反序列化等方式实现。
本文将重点介绍在Java中进行数据的持久化和读取操作的几种方法。
一、文件操作1.1文件写入在Java中进行文件数据的持久化操作可以使用FileOutputStream 或者BufferedWriter等类来实现。
通过FileOutputStream类,可以将数据以字节的形式写入文件,示例代码如下:```javatry {String data = "Hello, World!";FileOutputStream fos = new FileOutputStream("data.txt");fos.write(data.getBytes());fos.close();} catch (IOException e) {e.printStackTrace();}```上述代码中,首先定义了一个字符串数据并赋值给data变量,然后通过FileOutputStream类打开文件输出流,并将字符串数据以字节形式写入文件中,最后关闭文件输出流。
1.2文件读取使用FileInputStream或者BufferedReader类可以实现对文件数据的读取操作。
示例代码如下:```javatry {FileInputStream fis = new FileInputStream("data.txt");int content;while ((content = fis.read()) != -1) {System.out.print((char) content);}fis.close();} catch (IOException e) {e.printStackTrace();}```上述代码中,首先使用FileInputStream类打开文件输入流,并定义一个整型变量content用于存储读取的字节数据。
java 读取外部配置文件的方法Java是一种面向对象的编程语言,具有广泛的应用领域。
在Java开发中,有时需要读取外部配置文件来获取一些参数或配置信息。
下面将介绍一些常见的Java读取外部配置文件的方法。
1. 使用Java的Properties类:Java的Properties类是处理属性文件的工具类,非常适合读取外部配置文件。
以下是一个简单的示例代码:```javaimport java.io.FileInputStream;import java.io.IOException;import java.util.Properties;public class ReadConfigFile {public static void main(String[] args) {Properties prop = new Properties();try {prop.load(new FileInputStream("config.properties"));String value1 = prop.getProperty("key1");String value2 = prop.getProperty("key2");// 使用读取到的配置信息进行后续操作} catch (IOException e) {e.printStackTrace();}}}```通过创建Properties对象并使用load()方法来读取配置文件,可以通过getProperty()方法获取配置文件中的具体键值对。
2. 使用Java的ResourceBundle类:ResourceBundle类提供了一种读取以属性键值对形式存储的配置文件的方式。
以下是一个简单的示例代码:```javaimport java.util.ResourceBundle;public class ReadConfigFile {public static void main(String[] args) {ResourceBundle bundle = ResourceBundle.getBundle("config");String value1 = bundle.getString("key1");String value2 = bundle.getString("key2");// 使用读取到的配置信息进行后续操作}}```使用getBundle()方法加载配置文件,通过getString()方法获取具体的配置信息。
Java编程琐事(11)——⽂件的读取、替换和保存实例程序:package com.solid.fileoper;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.util.ArrayList;import java.util.List;/*** 对某个⽬录下的html⽂件进⾏遍历,然后替换html⽂件中的源代码,然后保存修改之后的⽂件。
* @author solidwang**/public class FileReplace {private String sourceStr1 = "/hqapp/tcm/3/attachments/paper";private String replaceStr1 = "www.hq.unicom.local/tcm_unicom/tcm_unicom/3/attachments/paper";private String sourceStr2 = "http://www.unicom.local/tcm/3/ewebeditor/uploadfile";private String replaceStr2 = "http://www.unicom.local/tcm_unicom/3/ewebeditor/uploadfile";private String sourceStr3 = "http://www.unicom.local/tcm/ewebeditor/uploadfile";private String replaceStr3 = "http://www.unicom.local/tcm_unicom/3/ewebeditor/uploadfile";/*** 修改⽬录下的.html⽂件* @param filePath 读取⽂件路径* @param prefix ⽂件前缀* @param savePath ⽂件保存路径*/public void modifyFileInDirectory(String filePath, String savePath, String prefix) {List list = readFileInDirectory(filePath, prefix);try {for(int i=0; i<list.size(); i++) {readFile(filePath + list.get(i), savePath + list.get(i));System.out.println("读取了第" + (i+1) + "个⽂件,⽂件路径:" + filePath + list.get(i));}} catch (Exception e) {e.printStackTrace();}}/*** 读取⽂件并替换其中的路径,然后保存⽂件* @param filePath 读取⽂件路径* @param savePath 保存⽂件路径*/public void readFile(String filePath, String savePath) {BufferedReader br = null;BufferedWriter bw = null;String content = "";try {br = new BufferedReader(new FileReader(filePath));bw = new BufferedWriter(new FileWriter(savePath));String line;while((line = br.readLine()) != null && (line != "")) {content = line + br.readLine() + "/n";bw.write(content.replaceAll(sourceStr1, replaceStr1).replaceAll(sourceStr2, replaceStr2).replaceAll(sourceStr3, replaceStr3).replaceAll("null", ""));}bw.flush();} catch (Exception e) {e.printStackTrace();} finally {try {if(br != null) br.close();if(bw != null) bw.close();} catch (Exception e) {e.printStackTrace();}}}/*** 遍历某⽬录下的所有.html⽂件* @param filePath* @param prefix* @return html⽂件名数组*/public List readFileInDirectory(String filePath, String prefix) {File fileDir = new File(filePath);File[] files = fileDir.listFiles();List list = new ArrayList();for(int i=0; i<files.length; i++) {if(files[i].getName().startsWith("preview")) {list.add(files[i].getName());}}return list;}/*** 测试⽅法*/public static void main(String[] args) {FileReplace readFile = new FileReplace();readFile.modifyFileInDirectory("D:/backup/中国联通V1.0/3/papers/", "D:/test/3/papers/", ".html");}}。
一、概述在软件开发中,经常会遇到需要从文件中读取数据并存入对象中的情况,尤其是在使用Java语言进行编程时。
掌握Java从文件中读取数据并存入对象中的方法对于开发者来说是非常重要的。
本文将介绍Java中实现该功能的常用方法,并结合实例详细讲解。
二、使用Java读取文件的方法1. 使用File类和Scanner类读取文件Java中可以使用File类和Scanner类来读取文件中的数据。
首先通过File类创建文件对象,然后通过Scanner类来读取文件中的内容。
以下是一个简单的示例代码:```javaimport java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class ReadFromFile {public static void m本人n(String[] args) {try {File file = new File("data.txt");Scanner scanner = new Scanner(file);while (scanner.hasNextLine()) {String data = scanner.nextLine();System.out.println(data);}scanner.close();} catch (FileNotFoundException e) {System.out.println("File not found");e.printStackTrace();}}}```2. 使用BufferedReader类读取文件除了Scanner类,还可以使用BufferedReader类来读取文件中的数据。
与Scanner类不同,BufferedReader类提供了更高效的读取方式。
以下是一个使用BufferedReader类读取文件的示例代码:```javaimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class ReadFromFile {public static void m本人n(String[] args) {try {BufferedReader reader = new BufferedReader(new FileReader("data.txt"));String line = reader.readLine();while (line != null) {System.out.println(line);line = reader.readLine();}reader.close();} catch (IOException e) {System.out.println("IO Exception");e.printStackTrace();}}}```以上是使用Java读取文件的基本方法,开发者可以根据实际需求选择合适的方式来读取文件中的数据。
java中复制对象的方法Java中复制对象的方法在Java中,复制对象是一个常见的操作。
复制对象可以理解为创建一个与原始对象具有相同属性和值的新对象。
Java提供了多种方法来实现对象的复制,本文将介绍几种常用的方法。
1. 使用构造方法复制对象一种简单的复制对象的方法是使用构造方法。
可以在新对象的构造方法中传入原始对象的属性值,从而创建一个新对象。
例如:```javapublic class Person {private String name;private int age;public Person(String name, int age) { = name;this.age = age;}// 省略getter和setter方法}public class Main {public static void main(String[] args) {Person p1 = new Person("Alice", 20);Person p2 = new Person(p1.getName(), p1.getAge());System.out.println(p2.getName()); // 输出:AliceSystem.out.println(p2.getAge()); // 输出:20}}```在上述代码中,我们通过传入p1对象的属性值来创建了一个新的p2对象。
通过这种方式,我们可以复制一个新对象,但是需要手动传入每个属性的值,比较繁琐。
2. 使用clone()方法复制对象Java中的Object类提供了一个clone()方法,可以用于复制对象。
为了使用clone()方法,需要实现Cloneable接口,并重写clone()方法。
例如:```javapublic class Person implements Cloneable {private String name;private int age;public Person(String name, int age) { = name;this.age = age;}@Overridepublic Object clone() throws CloneNotSupportedException {return super.clone();}// 省略getter和setter方法}public class Main {public static void main(String[] args) throws CloneNotSupportedException {Person p1 = new Person("Alice", 20);Person p2 = (Person) p1.clone();System.out.println(p2.getName()); // 输出:AliceSystem.out.println(p2.getAge()); // 输出:20}}```在上述代码中,我们实现了Cloneable接口,并重写了clone()方法。
java urltofile简书URLToFile是一个常用的Java类,它提供了将URL链接转换为本地文件的功能。
在实际应用中,我们经常会遇到需要将网络上的文件保存到本地的情况,这时就可以利用URLToFile完成这个任务。
URLToFile的主要作用是将Java的URL对象转换为本地的File对象,并保存到指定的路径上。
它可以用来下载网络上的文件,也可以用来访问网络资源,并将获取到的数据保存到本地文件中。
在使用URLToFile之前,我们首先需要确保我们已经创建了一个URL对象,并将需要下载或访问的链接传入URL的构造函数中。
接下来,我们可以调用URL的openConnection()方法来建立与指定URL的连接,并返回一个URLConnection对象。
URLConnection是一个抽象类,它表示一个到URL资源的通信链接,可以用于读取或写入资源的内容。
我们可以通过调用URL对象的openConnection()方法来创建一个URLConnection对象,并且调用其connect()方法来连接到指定URL。
一旦我们建立了与URL的连接,我们就可以通过URLConnection对象获取输入流来下载或访问网络上的文件。
我们可以使用InputStream来读取来自网络资源的数据,然后将其写入本地文件中。
为了方便处理,我们可以借助使用BufferedReader来读取数据,并使用BufferedWriter来写入数据到本地文件。
在读取和写入数据的过程中,我们还可以使用一些常用的Java类库来对数据进行处理。
例如,我们可以使用字节流或字符流,使用字节缓冲区和字符缓冲区来提高读取和写入的效率。
此外,我们还可以使用一些常见的类库来处理网络链接的异常情况,如IOException等。
最后,我们需要注意一些使用URLToFile的注意事项。
首先,我们需要确保网络链接是可用的,并且我们有相应的权限来访问指定的URL链接。
1.保存对象到文件中
Java语言只能将实现了Serializable接口的类的对象保存到文件中,利用如下方法即可:
public static void writeObjectToFile(Object obj)
{
File file =new File("test.dat");
FileOutputStream out;
try {
out = new FileOutputStream(file);
ObjectOutputStream objOut=new ObjectOutputStream(out); objOut.writeObject(obj);
objOut.flush();
objOut.close();
System.out.println("write object success!");
} catch (IOException e) {
System.out.println("write object failed");
e.printStackTrace();
}
}
参数obj一定要实现Serializable接口,否则会抛出
java.io.NotSerializableException异常。
另外,如果写入的对象是一个容器,例如List、Map,也要保证容器中的每个元素也都是实现了Serializable 接口。
例如,如果按照如下方法声明一个Hashmap,并调用writeObjectToFile方法就会抛出异常。
但是如果是
Hashmap<String,String>就不会出问题,因为String类已经实现了Serializable接口。
另外如果是自己创建的类,如果继承的基类没有实现Serializable,那么该类需要实现Serializable,否则也无法通过这种方法写入到文件中。
Object obj=new Object();
//failed,the object in map does not implement Serializable interface
HashMap<String, Object> objMap=new HashMap<String,Object>(); objMap.put("test", obj);
writeObjectToFile(objMap);
2.从文件中读取对象
可以利用如下方法从文件中读取对象
public static Object readObjectFromFile()
{
Object temp=null;
File file =new File("test.dat");
FileInputStream in;
try {
in = new FileInputStream(file);
ObjectInputStream objIn=new ObjectInputStream(in);
temp=objIn.readObject();
objIn.close();
System.out.println("read object success!"); } catch (IOException e) {
System.out.println("read object failed"); e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return temp;
}
读取到对象后,再根据对象的实际类型进行转换即可。