cityfile.java

来自「一次数据结构的课程设计」· Java 代码 · 共 175 行

JAVA
175
字号
package src;

import java.io.*;

class cityFile
{
	private final int MAX = 100;
	private String 	cityinfoFile = "resources/city.txt";
	private String  citynameFile = "resources/cityname.txt";
	DataInputStream input;
	DataOutputStream output;
//写入图信息
	public boolean outputtoInfoFile(Record records)
	{
		try
		{
			output = new DataOutputStream(new FileOutputStream(cityinfoFile));
		}
		catch(IOException e)
		{
			System.out.println("File not open");
			System.exit(1);
		}
		Record p = records.next;
		try
		{
			while(p!=null)
			{
				output.writeInt(p.from);
				output.writeInt(p.to);
				output.writeInt(p.distance);
				output.writeInt(p.cash);
				output.writeUTF(p.name);
				p = p.next;
			}
		}
		catch(IOException e)
		{
			System.err.println("Error during write to file");
			System.exit(1);
		}

		try
		{
			output.flush();
			output.close();
		}
		catch(IOException e)
		{
			System.err.println("File not closed properly");
			System.exit(1);
		}
		return true;
	}
//读出图信息
	public boolean inputfromInfoFile(Graph g)
	{
		try
		{
			input = new DataInputStream(new FileInputStream(cityinfoFile));

		}
		catch(IOException e)
		{
			System.out.println("File not open");
			return false;          //文件没有打开or没建立文件
		}
		try
		{
			while(true)
			{
				g.insertEdge(input.readInt(),input.readInt(),
									input.readInt(),input.readInt(),input.readUTF());
			}
		}
		catch(IOException eof)
		{
		}

		try
		{
			input.close();
		}
		catch(IOException e)
		{
			System.err.println("File not close property");
			System.exit(1);
		}
		return true;
	}

//读出城市信息
	public String[] inputfromNameFile()
	{

		int counter = 0;
		String[] name = new String[MAX];

		try
		{
			input = new DataInputStream(new FileInputStream(citynameFile));
		}
		catch(IOException e)
		{
			System.out.println("cityname.txt not exist");
		}
		try
		{
			while(true)
			{
				name[counter] = new String(input.readUTF());
				counter++;
			}
		}
		catch(IOException eof)
		{
		}

		try
		{
			input.close();
		}
		catch(IOException e)
		{
			System.err.println("cityname.txt not close property");
			System.exit(1);
		}

		String[]temp = new String[counter];
		for(int i=0;i<counter;i++)
			temp[i] = name[i];
		return temp;
	}
//写入城市信息
	public boolean outtoNameFile(String[] name,int num)
	{
		try
		{
			output = new DataOutputStream(new FileOutputStream(citynameFile));
		}
		catch(IOException e)
		{
			System.out.println("cityname.txt not open");
			System.exit(1);
		}
		int i = 0;

		try
		{
			while(i<num)
			{
				output.writeUTF(name[i]);
				i++;
			}
		}
		catch(IOException e)
		{
			System.err.println("wrong during write to cityname.txt");
			return false;
		}

		try
		{
			output.close();
		}
		catch(IOException e)
		{
			System.err.println("File not close property");
			System.exit(1);
		}
			return true;
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?