我在Java中使用接口构建了一个读取器

时间:2014-03-21 00:22:48

标签: java interface

我正试图让它成为我的程序

  • 选择一个文件
  • 一次读取一行代码
  • 使用界面做三件事
    • 转换为大写
    • 计算字符数
    • 保存到文件(“copy.txt”)

我坚持使用格式化部分。例如,我不确定println命令需要在哪里。任何帮助肯定会受到赞赏。我是初学者,还在学习基本的东西。

处理单个字符串的界面:

public interface StringProcessor
{
void process(String s);
}

处理类:

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.JFileChooser;
class FileProcessor
{
private Scanner infile;
public FileProcessor(File f) throws FileNotFoundException
{
    Scanner infile = new Scanner(System.in);
    String line = infile.nextLine();
}
public String go(StringProcessor a)
{
    a.process(line);
}
}

驱动程序类:

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.JFileChooser;

public class Driver
{
public static void main(String[] args) throws FileNotFoundException
{
    JFileChooser chooser = new JFileChooser();
    File inputFile = null;
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
    {
        inputFile = chooser.getSelectedFile();
    }
    FileProcessor infile = new FileProcessor(inputFile);
    int total=0;
}
}

这会使每行大写:

public class Upper implements StringProcessor
{
public void process(String s)
{
    while (infile.hasNextLine())
    {
        System.out.println(infile.nextLine().toUpperCase());
    }
}
}

这会计算角色:

public class Count implements StringProcessor
{
public void process(String s)
{
    while (infile.hasNextLine())
    {
        int charactercounter = infile.nextLine().length();
        total = total+charactercounter;
    }
}
}

这会打印到文件:

import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class Print implements StringProcessor
{
public void process(String s)
{
    PrintWriter out = new PrintWriter("copy.txt");
    while (infile.hasNextLine())
    {
        out.println(infile.nextLine());
    }
    out.close();
}
}

2 个答案:

答案 0 :(得分:2)

Java是我学过的第一批编程语言之一,一旦你得到它,它就是如此美丽。这是你作业的解决方案,但现在你有了新的家庭作业。去弄清楚什么在做什么,并用笔记标记。因此,下次遇到类似问题时,您可以查看旧代码并选择所需内容。我们在某些时候都是新手,所以不要把它弄坏。

<强> StringProcessor.java

public interface StringProcessor {

     public String Upper(String str);
     public int Count(String str);
     public void Save(String str, String filename);

}

<强> FileProcessor.java

import java.io.FileWriter;

public class FileProcessor implements StringProcessor{

public FileProcessor(){

}

// Here we get passed a string and make it UpperCase
@Override
public String Upper(String str) {

    return str.toUpperCase();
}

// Here we get passed a string and return the length of it
@Override
public int Count(String str) {

    return str.length();
}

// Here we get a string and a file name to save it as
@Override
public void Save(String str, String filename) {
    try{
        FileWriter fw = new FileWriter(filename);

        fw.write(str);
        fw.flush();
        fw.close();

    }catch (Exception e){
        System.err.println("Error: "+e.getMessage());
        System.err.println("Error: " +e.toString());
    }finally{
        System.out.println ("Output file has been created: " + filename);
    }

}

}

<强> Driver.java

import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;

public class Driver {

@SuppressWarnings("resource")
public static void main(String[] args){
    System.out.println("Welcome to the File Processor");

    Scanner scan = new Scanner(System.in);

    System.out.print("\nWould you like to begin? (yes or no): ");

    String startProgram = scan.next();

    if(startProgram.equalsIgnoreCase("yes")){

        System.out.println("\nSelect a file.\n");

        JFileChooser chooser = new JFileChooser();
        File inputFile = null;

        if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){

            inputFile = new File(chooser.getSelectedFile().getAbsolutePath());
            try{
            Scanner file = new Scanner(inputFile);
            file.useDelimiter("\n");
            String data = "";
            FileProcessor fp = new FileProcessor();

            while (file.hasNext()){

                String line = file.next();
                System.out.println("Original: " +line);
                System.out.println("To Upper Case: " +fp.Upper(line));
                System.out.println("Count: " +fp.Count(line));
                System.out.println();
                data += line;
            }


            System.out.println("\nFile Processing complete!\n");
            System.out.print("Save copy of file? (yes or no): ");

            String save = scan.next();

            if(save.equalsIgnoreCase("yes")){

                fp.Save(data, "copy.txt");
                System.out.println("\nProgram Ending... Goodbye!");
            }else{
                System.out.println("\nProgram Ending... Goodbye!");
            }

            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }else{

        System.out.println("\nProgram Ending... Goodbye!");
    }

}
}

<强>的text.txt

some text here to test the file
and to see if it work correctly

保存文件“copy.txt”只是一个注释,它将显示在项目文件夹中。

答案 1 :(得分:1)

由于您的问题在字符流上运行,因此已经有一个很好的Java接口可以实现。实际上,它们是两个抽象类:FilterReaderFilterWriter - 任何一个都可以工作。在这里,我选择扩展FilterWriter

例如,这是一个Writer示例,用于跟踪要求写入的字符数:

import java.io.*;

public class CharacterCountingWriter extends FilterWriter {
    private long charCount = 0;

    public CharacterCountingWriter(Writer out) {
        super(out);
    }

    public void write(int c) throws IOException {
        this.charCount++;
        out.write(c);
    }

    public void write(char[] buf, int off, int len) throws IOException {
        this.charCount += len;
        out.write(buf, off, len);
    }

    public void write(String str, int off, int len) throws IOException {
        this.charCount += len;
        out.write(str, off, len);
    }

    public void resetCharCount() {
        this.charCount = 0;
    }

    public long getCharCount() {
        return this.charCount;
    }

}

基于该模型,您也应该能够实现UpperCaseFilterWriter

使用这些类,这是一个复制文件的程序,在文本上加上文本并在每行中打印字符数。

public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new FileReader(args[0]));

    try (CharacterCountingWriter ccw = new CharacterCountingWriter(new FileWriter(args[1]));
         UpperCaseFilterWriter ucfw = new UpperCaseFilterWriter(ccw);
         Writer pipeline = ucfw) {  // pipeline is just a convenient alias

        String line;
        while (null != (line = in.readLine())) {
            // Print count of characters in each line, excluding the line
            // terminator
            ccw.resetCharCount();
            pipeline.write(line);
            System.out.println(ccw.getCharCount());
            pipeline.write(System.lineSeparator());
        }
        pipeline.flush();
    }
}