2

My teacher gave us homework to reverse a integer file. lets say I have a file that contains 1,2,3,4,5. My homework is to reverse it and write it into a file so it contains 5,4,3,2,1. I already did that with List. and it worked. But my teacher told me not to do it with List. Can someone help me please ?

static void getNumFiles(File file){
    InputStream inputStream = null;
    OutputStream outputStream = null;
    List<Integer> list = new ArrayList<>();

    int actuallyRead = 0;
    byte[] buffer = new byte[4];
    int[] arr = new int[list.size()];
    int counter = list.size();
    int x = 0;
    try {
        inputStream = new FileInputStream(file);

        outputStream = new FileOutputStream(file);


        while((actuallyRead = inputStream.read(buffer)) != -1){
            x = ByteBuffer.wrap(buffer).getInt();
            list.add(x);
        }

        for (int i = 0; i < arr.length; i++) {
            arr[i] = list.get(list.size() - i) ;
        }

        exampleWriteIntegerArray(arr, file);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Sufferring
  • 49
  • 5
  • Hi, can you show us the code and the file that you are currently using by [edit]ing your question? That would make it easier to know exactly what you are currently doing and give us an idea about what your teacher wanted you to do. Did your teacher say something else? Maybe you just learned about something new in class and he wanted you to apply that to the task? – Secespitus Sep 06 '19 at 07:59
  • [How to read file from end to start (in reverse order) in Java?](https://stackoverflow.com/questions/8664705/how-to-read-file-from-end-to-start-in-reverse-order-in-java) – Sudhir Ojha Sep 06 '19 at 07:59
  • 4
    Clarify what your teacher wants with your teacher. – Andy Turner Sep 06 '19 at 07:59
  • i edited my question. its basically adds the written int to a list. and then add them to a reversed array and get written again. bute its backwards now – Sufferring Sep 06 '19 at 08:17
  • Think of a string reversal program ? – Kris Sep 06 '19 at 08:22
  • It looks like it's a binary file, not a text file containing the integers as strings? – daniu Sep 06 '19 at 08:26
  • 2
    1 - ask your teacher for help - that's what he is paid for, no? 2 - ask him what he wants you to use - List would be the better choise IMO 3 - clarify what should happen with a file having `10,20,30` shold it result in `30,20,10` or `03,02,01`? – user85421 Sep 06 '19 at 08:31
  • @Kris its a bin file. not text. so i dont know if string is the right choice. daniu is a file that contains ints. Carlos Heuberger, the result should be 30,20,10 – Sufferring Sep 07 '19 at 07:23

3 Answers3

1

This answer assumes the file in question is a simple text file. The file type was not clear in the original question.

Just a quick snippet of code that achieves your assignment without using a list. It reads the input file and uses a StringBuilder to reverse the input. The reversed input can then be written to a desired output location.

public static void main(final String[] args) {
    try {
        String fileContent = new String(Files.readAllBytes(Paths.get("D:/12345.txt"))); // Read file
        StringBuilder sb = new StringBuilder(fileContent);
        String reversedContent = sb.reverse().toString();
        PrintWriter writer = new PrintWriter(new File("D:/54321.txt")); // Create new file and output the reversed String.
        writer.println(reversedContent);
        writer.close();
    }
    catch (IOException ex) {
        ex.printStackTrace();
    }
}

Input: 1,2,3,4,5 Output: 5,4,3,2,1

Snagtz
  • 118
  • 6
0

It's not entirely clear from your question what exactly your teacher expects from you. Also, it looks like the file is a binary file with integers rather than a text file with integer values. If that is true, without writing the program for you:

Open your file as a RandomAccessFile.

Use its length() function to determine how many integers are contained in it (Note that the length is in bytes, while integers are 32 bit).

Move to the last int position in the file using the seek() method, read it using readInt(), output it.

Move one position before that, do the same, until you're at position 0 - at which point you've read the whole file.

daniu
  • 14,137
  • 4
  • 32
  • 53
0

If you use String's reverse function then you cannot handle the following situation 250,150,623changes to 326,051,052.

And also I cannot clearly understand the your files context. Does it contains the , character for delimiter character? If not, what is your file's delimiter?

At the beginning of my answer I said that you cannot handle that. However, if you know what is your files delimiter then you can use @ProfessionalCode's code with that extras,

public static void main(final String[] args) {
    try {
         String fileContent = new String(Files.readAllBytes(Paths.get("D:/12345.txt"))); // Read file
         StringBuilder sb = new StringBuilder(fileContent);
         String reversedContent = sb.reverse().toString();
         char delimiter = " "; //let say it is whitespace 
         String temp = ""; //it will use between two delimiters to get reverse String
         PrintWriter writer = new PrintWriter(new File("D:/54321.txt")); // Create new file and output the reversed String
         for (int i = 0; i < reversedContent.length(); i++){
             if(reverseContent.charAt(i) == delimiter){
                 writer.print(temp.reverse().toString());
                 writer.print(delimiter.reverse().toString()); //writing your delimiter between all numbers, if it is like ",-" it needed to be reversed to "-,"
                 temp = "";
             }else{
                 temp += reverseContent.charAt(i);
             }
         }
         writer.print(temp.reverse().toString()); //for last number
         writer.close();
    }catch (IOException ex) {
         ex.printStackTrace();
    }

}
Burak
  • 13
  • 4