3

就像我做的一个类似的项目一样,这个项目是从一个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");
          }
       }
}

所以这里是来自堆栈跟踪的信息:

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

5 回答 5

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) {
            }
        }


    }


}
于 2013-04-22T02:31:11.027 回答
3

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

java ReverseFile source.txt target.txt

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

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

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

于 2013-04-22T02:20:11.737 回答
0

这是您的问题的无错误解决方案,您使用“扫描仪”而不导入“util”包。我们开始:-----------

   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");
      }
   }
      }
于 2014-08-07T11:12:08.780 回答
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);
}

}
于 2016-03-12T21:03:32.750 回答
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");
		}
	}
}

输出:在此处输入图像描述

于 2019-03-25T10:09:07.147 回答