How do I read Windows NTFS's Alternate Data Stream using Java's IO?

限于喜欢 提交于 2019-12-04 17:47:45

I was able to read the ADS of a file simply by opening the the file with the syntax "file_name:stream_name". So if you've done this:

C:>echo Hidden text > test.txt:hidden

Then you should be able to do this:

package net.snortum.play;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class AdsPlay {
    public static void main(String[] args) {
        new AdsPlay().start();
    }

    private void start() {
        File file = new File("test.txt:hidden");
        try (BufferedReader bf = new BufferedReader( new FileReader(file))) {
            String hidden = bf.readLine();
            System.out.println(hidden);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If you want to get the ADS data from the dir /r command, I think you just need to execute a shell and capture the output:

package net.snortum.play;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExecPlay {

    public static void main(String[] args) {
        new ExecPlay().start();
    }

    private void start() {
        String fileName = "not found";
        String ads = "not found";
        final String command = "cmd.exe /c dir /r"; // listing of current directory

        final Pattern pattern = Pattern.compile(
                  "\\s*"                 // any amount of whitespace
                + "[0123456789,]+\\s*"   // digits (with possible comma), whitespace
                + "([^:]+):"             // group 1 = file name, then colon
                + "([^:]+):"             // group 2 = ADS, then colon
                + ".+");                 // everything else

        try {
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor();
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;

                while ((line = br.readLine()) != null) {
                    Matcher matcher = pattern.matcher(line);
                    if (matcher.matches()) {
                        fileName = matcher.group(1);
                        ads = matcher.group(2);
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(fileName + ", " + ads);

    }
}

Now you can use the first code listing to print the ADS data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!