java读写

text.txt文件里有很多数据,每行里有一条数据:第一行:小名,第二行:xiaoming,第三行:xiaomao。。,如何读取text.txt里的数据,将小名转化为拼音,英文不做处理,即小名---->xiaoming,xiao ming,xiao ming hao,xiaominghao,然后和text.txt里的数据比对,如果text里有xiaoming,则将小名=xiaoming,写入text1.txt文件里,求全部代码,

[code="java"]
package com.carvin.questions;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class Spell {
/**
* 获取汉字串拼音,英文字符不变
*
* @param chinese
* 汉字串
* @return 汉语拼音
*/
public static String cn2Spell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i],
defaultFormat)[0]);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
return pybf.toString();
}

/**
 * 获取汉字串拼音List,英文字符不变
 * 
 * @param chinese
 *            汉字串
 * @return 汉语拼音
 */
public static List<String> cn2SpellList(String chinese) {
    if(chinese == null || chinese.trim().equals("")) {
        throw new IllegalArgumentException("chinese name is not null and empty");
    }

    String tempChinese = chinese.trim().replaceAll("\\s*", "");
    int len = tempChinese.length();
    List<String> spellList = new ArrayList<String>();

    List<String> combinationList = getCombinationList(len - 1);
    for(int i=0, getCombinationListLen=combinationList.size(); i<getCombinationListLen; i++) {
        String combinationStr = combinationList.get(i);
        StringBuilder strBuilder = new StringBuilder();
        for(int j=0; j<len; j++) {
            strBuilder.append(tempChinese.charAt(j));
            if(j != len - 1 && combinationStr.charAt(j) == '1') {
                strBuilder.append(" ");
            }
        }
        spellList.add(cn2Spell(strBuilder.toString()));
    }
    return spellList;
}

private static List<String> getCombinationList(int spaceCount) {
    int count = 2 << (spaceCount-1);
    List<String> combinationList = new ArrayList<String>();
    int maxLen = 0;
    for(int i=0; i<count; i++) {
        String binaryString = Integer.toBinaryString(i);
        int len = binaryString.length();
        if(len > maxLen) {
            maxLen = len;
        }
        combinationList.add(binaryString);
    }

    for(int j=0; j<count; j++) {
        String combination = combinationList.get(j);
        int len = combination.length();
        if(len < maxLen) {
            for(int index=len; index<maxLen; index++) {
                combination = "0" + combination;
            }
            combinationList.set(j, combination);
        }
    }

    return combinationList;
}

/**
 * 判断字符串是否包含有中文
 * @param str 字符串
 * @return 包含返回true 不包含返回false
 */
public static boolean hasCn(String str) {
    String regEx = "[\\u4e00-\\u9fa5]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(str);
    return m.find();
}

public static void main(String[] args) throws Exception {
    BufferedReader bufferedReader = null;
    BufferedWriter bufferedWriter = null;
    try {
        bufferedReader = new BufferedReader(new FileReader("D:/text.txt"));
        bufferedWriter = new BufferedWriter(new FileWriter("D:/text1.txt"));
        List<String> keyList = new ArrayList<String>();
        Map<String, List<String>> valueMap = new TreeMap<String, List<String>>();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            line = line.trim();
            if(hasCn(line)) {
                valueMap.put(line, cn2SpellList(line));
            } else {
                keyList.add(line);
            }
        }

        for(String name : valueMap.keySet()) {
            List<String> valueList = valueMap.get(name);

            for(String spell : valueList) {
                if(keyList.contains(spell)) {
                    String result = name + "=" + spell + "\n";
                    bufferedWriter.write(result);
                }
            }
        }
    } finally {
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        if (bufferedWriter != null) {
            bufferedWriter.close();
        }
    }
}

}

[/code]

测试结果:
text.txt文件内容
小名
xiaomao
xiaoqing
xiaoming
xiao ming
xiaominghao
xiao ming hao
xiaoming hao
小毛
xiao mao

text1.txt文件内容
小名=xiaoming
小名=xiaominghao
小名=xiaoming hao
小名=xiao ming
小名=xiao ming hao
小毛=xiaomao
小毛=xiao mao

:D 我要分数!
如果效果不对,请说明。。。
我要分数! :oops: :wink:

代码:

package com.xiaoming;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileTest {
public static void main(String[] args) {
File file = new File("text1.txt");

try {
// 指定写到哪个文件里去
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

            BufferedReader br = new BufferedReader(new FileReader("text.txt"));
            String s = null;
            int i=0;
            while ((s = br.readLine()) != null) {               
                if("xiaoming".equals(s) ||"小名".equals(s) ){                     
                    i++;
                }                   
            }
            if(i>0){//
                bw.write("小名=xiaoming");
            }
            // 刷新缓冲
            bw.flush();
            bw.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

}

感觉楼上理解不对
就是第四行是王晓明 你怎么办?
这个要用到一个pinyin4j这个jar去转的
判断是不是汉字 如果是汉字就将汉字转换成拼音
读写没什么好说的了!

直接读text.txt
//String str =readline();
//使用汉字转拼音的jar包 str 转为拼音字母
//add to list1
//判断list1中有没有
//有放入list2

//最后把list2的所有东西都写入text2.txt

直接使用pinyin4j.jar啊,难道你自己去转么

代码直接给你,这样不是很好嘛。。。
你就想先好思路,比如自己写个伪代码,写好要做什么,然后一步步的来

代码贴上来,帮你改~

需要用到包pinyin4j.jar

[code="java"]
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class Spell {
/**
* 获取汉字串拼音,英文字符不变
*
* @param chinese
* 汉字串
* @return 汉语拼音
*/
public static String cn2Spell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i],
defaultFormat)[0]);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
return pybf.toString();
}

/**
 * 判断字符串是否包含有中文
 * @param str 字符串
 * @return 包含返回true 不包含返回false
 */
public static boolean hasCn(String str) {
    String regEx = "[\\u4e00-\\u9fa5]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(str);
    return m.find();
}

public static void main(String[] args) throws Exception {
    BufferedReader bufferedReader = null;
    BufferedWriter bufferedWriter = null;
    try {
        bufferedReader = new BufferedReader(new FileReader("D:/text.txt"));
        bufferedWriter = new BufferedWriter(new FileWriter("D:/text1.txt"));
        List<String> keyList = new ArrayList<String>();
        List<String> valueList = new ArrayList<String>();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            line = line.trim();
            keyList.add(line);
            valueList.add(cn2Spell(line));
        }

        for (int i = 0, len = keyList.size(); i < len; i++) {
            String key = keyList.get(i);
            if(hasCn(key)) {
                String value = valueList.get(i);
                if (keyList.contains(value)) {
                    String result = keyList.get(i) + "=" + value + "\n";
                    bufferedWriter.write(result);
                }
            }
        }
    } finally {
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        if (bufferedWriter != null) {
            bufferedWriter.close();
        }
    }
}

}

[/code]

测试结果:
text.txt 内容:
小名
xiaomao
xiaoqing
xiaoming
小毛

text1.txt 内容:
小名=xiaoming
小毛=xiaomao

pingyin4j我用的2.5.0, 下载地址:[url]http://www.pc6.com/softview/SoftView_51633.html[/url]
cn2Spell方法参考:[url]http://lavasoft.blog.51cto.com/62575/178320[/url]

[quote]要是这个中文转拼音,返回list呢[/quote]

不太明白什么意思? 是要哪个返回List呢?

[code="java"]package com.wlh.lucene.test2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class Test {
//源文件与目标文件的全路径名
private static final String READ_FILE="E:/workspace65/paoding-analysis_test/src/com/wlh/lucene/test2/txt.txt";
private static final String WRITE_FILE="E:/workspace65/paoding-analysis_test/src/com/wlh/lucene/test2/txt1.txt";
private static HanyuPinyinOutputFormat spellFormat = new HanyuPinyinOutputFormat();

private static BufferedWriter writer = null;
private static BufferedReader reader = null;
//初始化信息
public static void init() throws IOException{
writer = new BufferedWriter(new FileWriter(new File(WRITE_FILE),false));
reader = new BufferedReader(new FileReader(new File(READ_FILE)));

spellFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);

spellFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

spellFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
}
// 判断字符串是否包含有中文
public static boolean isChinese(String str) {

String regex = "[\u4e00-\u9fa5]";

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(str);

return matcher.find();

}

//使用PinYin4j.jar将汉字转换为拼音
public static String chineneToSpell(String chineseStr){
return PinyinHelper.toHanyuPinyinString(chineseStr , spellFormat ,"");
}
//将转换后的字符串写入目标文件
public static void writeToFile(String spellStr) throws IOException{
writer.write(spellStr);
}
//从源文件读取按行数据
public static void readFromFile() throws IOException{
String line = null;
while ((line = reader.readLine()) != null) {

line = line.trim();

//是中文
if(isChinese(line)){
line = chineneToSpell(line);
}
writeToFile(line + "\n");
}

}
//关闭文件流
public static void destory() throws IOException{
reader.close();
writer.close();
}
public static void main(String[] args) throws IOException {
init();
readFromFile();
destory();
}
}
[/code]

不好意思。main有些变化没有发上去。

[code="java"]
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
bufferedReader = new BufferedReader(new FileReader("D:/text.txt"));
bufferedWriter = new BufferedWriter(new FileWriter("D:/text1.txt"));
List keyList = new ArrayList();
Map> valueMap = new TreeMap>();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
line = line.trim();
if(hasCn(line)) {
valueMap.put(line, cn2SpellList(line));
} else {
keyList.add(line);
}
}

        for(String name : valueMap.keySet()) {
            List<String> valueList = valueMap.get(name);

            for(String spell : valueList) {
                for(String key : keyList) {
                    if(key.contains(spell)) {
                        String result = name + "=" + key + "\n";
                        bufferedWriter.write(result);
                    }
                }
            }
        }
    } finally {
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        if (bufferedWriter != null) {
            bufferedWriter.close();
        }
    }
}

[/code]