首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从一个文本文件读取并写入两个文本文件

从一个文本文件读取并写入两个文本文件
EN

Stack Overflow用户
提问于 2020-07-02 01:11:08
回答 1查看 54关注 0票数 0

我需要读取一个文本文件(carsAndBikes.txt),在cars.txt或bikes.txt carsAndBikes中的写入包含汽车和自行车的列表,每个名称的第一个字符是C或B (C代表汽车,B代表自行车)。到目前为止,我有,但它显示汽车和自行车的内容。而不是分开的内容。(仅限汽车或仅限自行车)

代码语言:javascript
复制
   public static void separateCarsAndBikes(String filename) throws FileNotFoundException, IOException
    {
        //complete the body of this method to create two text files
        //cars.txt will contain only cars
        //bikes.txt will contain only bikes    
        
        File fr = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
        Scanner scanFile = new Scanner(fr);                                                             
        String line;
                       
        while(scanFile.hasNextLine())
        {
            line = scanFile.nextLine();
            if(line.startsWith("C"))
            {
               
                try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\cars.txt"))
                {                  
                   printWriter.write(line);                                                                           
                }
                catch(Exception e)
                {
                    System.out.println("Message" + e);
                }
            }
            else
            {
                
                try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\bikes.txt"))
                {                                       
                    printWriter.write(line);                  
                }
                catch(Exception e)
                {
                    System.out.println("Message" + e);
                }               
            }            
        } 
        //close the file
       scanFile.close();      
    }        
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-02 01:25:55

您正在检查输入文件名是否以c开头,而不是检查读取行是否以c开头。

您还应该在循环之前打开这两个输出文件,并在循环之后关闭它们。

代码语言:javascript
复制
// Open input file for reading 
File file = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");      
BufferedReader br = new BufferedReader(new FileReader(file))); 

// Open bike outputfile for writing
// Open cars outputfile for writing

// loop over input file contents
String line;
while( line = br.readLine()) != null ) {

    // check the start of line for the character
    if (line.startsWith("C") {
        // write to cars
    } else {
        // write to bikes
    }
}

// close all files
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62682013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档