如何读取文件,反转顺序,以及写入相反的顺序

时间:2013-04-22 02:04:39

标签: java file-io indexoutofboundsexception

就像我制作的类似项目一样,这个项目是从txt文件中读取字符,颠倒字符串的顺序并将其重写为另一个txt文件。但它一直在输出我的“出问题”的例外。任何人都可以帮我解决出错的问题吗?

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class ReverseFile
{
    public static void main(String[] args) throws IOException
       {
          try{
          String source = args[0];
          String target = args[1];

          File sourceFile=new File(source);

          Scanner content=new Scanner(sourceFile);
          PrintWriter pwriter =new PrintWriter(target);

          while(content.hasNextLine())
          {
             String s=content.nextLine();
             StringBuffer buffer = new StringBuffer(s);
             buffer=buffer.reverse();
             String rs=buffer.toString();
             pwriter.println(rs);
          }
          content.close();    
          pwriter.close();
          System.out.println("File is copied successful!");
          }

          catch(Exception e){
              System.out.println("Something went wrong");
          }
       }
}

所以这是来自stacktrace的信息:

java.lang.ArrayIndexOutOfBoundsException: 0
    at ReverseFile.main(ReverseFile.java:36)

5 个答案:

答案 0 :(得分:3)

您需要在运行程序时在命令行上指定文件名(源和目标)。

java ReverseFile source.txt target.txt

在您的程序中,您尝试从命令行中读取文件名称

String source = args[0];
String target = args[1];

因此,如果您没有在那里指定这些名称,java会尝试访问索引0和1处的数组args,这些数组为空,您将获得ArrayIndexOutOfBoundsException

答案 1 :(得分:3)

我对您的环境不太确定,以及文本可能有多长。而且我也不确定你为什么需要扫描仪?

无论如何,这是我对这个问题的看法,希望这会对你有所帮助:)。

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;


public class Reverse {

    public static void main(String[] args) {

        FileInputStream fis = null;
        RandomAccessFile raf = null;

        // by default, let's use utf-8
        String characterEncoding = "utf-8";

        // but if you pass an optional 3rd parameter, we use that
        if(args.length==3) {
            characterEncoding = args[2];
        }

        try{

            // input file
            File in = new File(args[0]);
            fis = new FileInputStream(in);

            // a reader, because it respects character encoding etc
            Reader r = new InputStreamReader(fis,characterEncoding);

            // an outputfile 
            File out = new File(args[1]);

            // and a random access file of the same size as the input, so we can write in reverse order 
            raf = new RandomAccessFile(out, "rw");
            raf.setLength(in.length());

            // a buffer for the chars we want to read 
            char[] buff = new char[1];

            // keep track of the current position (we're going backwards, so we start at the end)
            long position = in.length(); 

            // Reader.read will return -1 when it reached the end.
            while((r.read(buff))>-1) {

                // turn the character into bytes according to the character encoding
                Character c = buff[0];
                String s = c+"";
                byte[] bBuff = s.getBytes(characterEncoding);

                // go to the proper position in the random access file
                position = position-bBuff.length;
                raf.seek(position);

                // write one or more bytes for the character
                raf.write(bBuff);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // clean up
            try {
                fis.close();
            } catch (Exception e2) {
            }
            try {
                raf.close();
            } catch (Exception e2) {
            }
        }


    }


}

答案 2 :(得分:0)

这里是你的错误免费解决你的问题,你使用“扫描仪”而不导入“util” package.here我们去:-----------

   import java.io.*;
    import java.util.*;

        public class ReverseFile
         {
         public static void main(String[] args) throws IOException
          {
      try{
      File sourceFile=new File(args[0]);
      Scanner content=new Scanner(sourceFile);
      PrintWriter pwriter =new PrintWriter(args[1]);

      while(content.hasNextLine())
      {
         String s=content.nextLine();
         StringBuffer buffer = new StringBuffer(s);
         buffer=buffer.reverse();
         String rs=buffer.toString();
         pwriter.println(rs);
      }
      content.close();    
      pwriter.close();
      System.out.println("File is copied successful!");
      }

      catch(Exception e){
          System.out.println("Something went wrong");
      }
   }
      }

答案 3 :(得分:0)

想到一个简单的方法。

public class ReadFileReverse {

public int[] readByte(File _file) throws IOException {
    FileInputStream source = new FileInputStream(_file);
    int currentByte = source.available();
    int readCount = 0;

    int byteContainer[] = new int[currentByte];
    while(readCount < currentByte){
        byteContainer[readCount] = source.read();
        readCount++;
    }
    source.close();
    return byteContainer;
}

public void printReverse(int[] fileContent){
    for(int byt=fileContent.length -1; byt >= 0 ; byt--){
        System.out.print((char) fileContent[byt]);
    }
}

public static void main(String[] args) throws IOException {
    File fileToRead = new File("/README.txt");

    ReadFileReverse demo = new ReadFileReverse ();
    int[] readBytes = demo.readByte(fileToRead);

    demo.printReverse(readBytes);
}

}

答案 4 :(得分:0)

在这里,我们正在读取字符串变量中的文件,然后使String Builder对象有效地执行反向操作,然后打印

package com;

import java.io.FileReader;

public class Main {
	public static void main(String[] args) {

		try {
			FileReader fr = new FileReader("D:\\newfile.txt");
			String str = "";
			int ch;
            //reading characters in to string variable
			while ((ch = fr.read()) != -1) {
				str += Character.toString((char) ch);
			}
			System.out.println("Original String : " + str);
            //converting string variable to String Builder object
			StringBuilder sb = new StringBuilder(str);
            //reversing the string and printing
			System.out.println("Reverse order : " + sb.reverse());
			fr.close();
		} catch (Exception e) {
			System.out.println("error");
		}
	}
}

输出:enter image description here