最近写了个小程序,计算出txt文件的字节数,并重新写入新的txt,使格式整齐。具体的要求如下:原有文件是用TAB键分割的,现不要分割符了,还有注意定长是按字节算的,也就是一个中文是两个字节,一个数字或字母是一个字节。字段都是定长的,不足右补空格。
开发环境是vs2008。txt文件内容如下:
39031687 上海高等教育普通全日制院校专业设置目录:1985-1986 -G649.285.1-63/S322
39000968 马克思恩格斯列宁斯大林***著作大辞典.1 A-61/001/1
01264804 马克思主义百科要览.2 A-61/002/2
计算3个字段的字节数,如果txt文件时4个以上字段,再增加即可:
private int temp0 = 0, temp1 = 0, temp2 = 0; //最终显示字段结果
private int l0 = 0, l1 = 0, l2 = 0; //文件每个字段最长字节数
private void Btn_OpenFile_Click(object sender, EventArgs e)
{
string FileName;
if (this.openFileDialog1.ShowDialog() == DialogResult.OK) //打开文件
{
FileName = this.openFileDialog1.FileName;
if (FileName != "")
{
string newValue = string.Empty;
using (StreamReader read = new StreamReader(FileName, Encoding.GetEncoding("gb2312"))) //中文
{
do
{
newValue = read.ReadLine();
if (newValue != null)
{
string[] line = newValue.Split('\t'); //\t是以tab为分隔符
l0 = (System.Text.Encoding.Default.GetBytes(line[0])).Length; //第一个字段
l1 = (System.Text.Encoding.Default.GetBytes(line[1])).Length; //第二个字段
l2 = (System.Text.Encoding.Default.GetBytes(line[2])).Length; //第三个字段
if (l0 > temp0)
{
temp0 = l0;
}
if (l1 > temp1)
{
temp1 = l1;
}
if (l2 > temp2)
{
temp2 = l2;
}
}
}
while (newValue != null);
}
}
Tb_Show.Text = "文件中,三个字段的最大字节分别是:"+temp0+","+temp1+","+temp2+"。";
}
}
写入新的文件,完成格式要求
string FileName = openFileDialog1.FileName;
if (FileName != "")
{
string newValue = string.Empty;
using (StreamReader read = new StreamReader(FileName, Encoding.GetEncoding("gb2312")))
{
do
{
newValue = read.ReadLine();
if (newValue != null)
{
int m0, m1, m2;
string[] line = newValue.Split('\t');
l0 = (System.Text.Encoding.Default.GetBytes(line[0])).Length;
l1 = (System.Text.Encoding.Default.GetBytes(line[1])).Length;
l2 = (System.Text.Encoding.Default.GetBytes(line[2])).Length;
m0 = temp0 - l0;
m1 = temp1 - l1;
m2 = temp2 - l2;
if (!File.Exists(Application.StartupPath + " \\new.txt")) //文件保存在当前应用程序目录下,名字为new.txt
{
FileStream fs1 = new FileStream(Application.StartupPath + " \\new.txt", FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs1);
string s0 = line[0];
string s1 = line[1];
string s2 = line[2];
sw.Write(s0);
for (int i = 0; i < m0; i++)
{
sw.Write("\0");
}
sw.Write(s1);
for (int j = 0; j < m1; j++)
{
sw.Write("\0");
}
sw.Write(s2);
for (int k = 0; k < m2; k++)
{
sw.Write("\0");
}
sw.Write("\r\n");
sw.Close();
fs1.Close();
}
else
{
StreamWriter sw2 = File.AppendText(Application.StartupPath + " \\new.txt");
m0 = temp0 - l0;
string s0 = line[0];
string s1 = line[1];
string s2 = line[2];
sw2.Write(s0);
for (int i = 0; i < m0; i++)
{
sw2.Write("\0");
}
sw2.Write(s1);
for (int j = 0; j < m1; j++)
{
sw2.Write("\0");
}
sw2.Write(s2);
for (int k = 0; k < m2; k++)
{
sw2.Write("\0");
}
sw2.Write("\r\n");
sw2.Close();
}
}
}
while (newValue != null);
}
}
}
写的程序不足之处,请多多包涵,thanks...
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/20940190/viewspace-662014/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/20940190/viewspace-662014/