Is it possible to iterate through a binary file given a certain position specified by the user? I've been trying to think of a way to do this but I'm not finding any leads. Here is the code that I'm working on:
System.out.println("Enter name of file: ");
String filename = in.nextLine();
File file = new File(filename);
if (file.exists()) {
System.out.println(file.getAbsoluteFile());
RandomAccessFile raf = new RandomAccessFile(file, "r");
System.out.println("Size: " + file.length() + " bytes.");
System.out.println("Attempting to record file to AList");
AList<Byte> fileList = new AList<>();
raf.seek(0);
for (int i = 0; i < raf.length(); i++) {
fileList.add(raf.readByte());
}
System.out.print("Enter byte positon to navigate to: ");
long pos = in.nextLong();
in.nextLine();
ListIterator<Byte> itr = fileList.listIterator(0);
if (pos >= 0 && pos < file.length()){
int i = 0;
while(i < 5 && itr.hasNext() == true){
raf.seek(pos);
byte b = raf.readByte();
System.out.print(((b >= 0 && b <= 15)?"0":"") + Integer.toHexString((int)b & 0x00FF) + " ");
i++;
}
I'm not even entirely sure if what I've wrote is logically correct. What I'm trying to do is have the user specify a position in the binary file, then I check to see if thats within the files range. Then, it should be able to output the next 5 bytes from that position using an iterator. I'm not entirely sure about the iterator though.
You could just modify the loop reading the file to a) ignore the bytes up to the requested start position, b) read and print the next 5 bytes read, then c) exit.
Related
I have an string array of text file names. I would like to send this string array through an iterator and have it give me the first X number of characters of each text file. It would then put those strings in to an array that I can include in a list view.
I was planning on using a buffered reader to read the text and then substring it. But as for using the loops to go through each file, I am guessing that you would need to use a for loop or a foreach loop. However I am really unknowledgeable about how to use those.
Any help would be appreciated. Thanks!
Edit:
I should have added this earlier. I am using this to show what files have been downloaded and also to give them a preview of the text file. However, like I said above, some of them have not been downloaded. I would like to know which position in the filename array actually exist and to be able to put the retrieved strings in the proper places of the list view. Will this affect any of the current answers? Any ideas?
Let's name the variables you have:
String array: String filenames[]
x number of chars: int x
array of x chars in file: string chars[]. Assume you set each index to empty string.
import java.util.Scanner
public static void main(String[] args) {
Scanner fin = null;
// Loop through files
for(int i = 0; i < filenames.length; i++) {
// Open the file with a FileReader
fin = new Scanner(new BufferedReader(new FileReader(filenames[i])));
// Loop through x chars and add to string
for(int j = 0; j < x && fin.hasNext(); j++) {
chars[i] += fin.next();
}
// Close your file
fin.close();
}
}
Thanks for your help. This is what I ended up going with:
filenamearray = filenamefinal.split(";");
try {
List<String> results = new ArrayList<String>();
for (int i = 0; i < filenamearray.length; i++) {
File txt = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[i] + ".txt");
if (txt.exists()) {
txtread = new FileInputStream(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[i] + ".txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(txtread));
String text = reader.readLine();
displaytxt = text.substring(0, 45) + ". . ."
results.add(displaytxt);
} else {
results.add("empty");
}
}
finalversetextarray = new String[results.size()];
finalversetextarray = results.toArray(finalversetextarray);
I am trying to develop a program that searches for duplicate files using MD5 hash, it will compare two hash files for duplicate.
I am having difficulties comparing the two files, after hashing the files with MD5 hash code, I keep getting the error "Java.IO.FileNotFoundException.". Here is my code, I do not know what I am doing wrong.
////////////////////// It is a GUI Program ////////////////////////
DefaultListModel m = new DefaultListModel(); // List Model for displaying the hash codes
int rval = chooser.showOpenDialog(null); //JFileChooser for selecting files tobehashed
if(rval == JFileChooser.APPROVE_OPTION){
File f = chooser.getCurrentDirectory();
String fs = f + "";
if(!f.isDirectory()){
JOptionPane.showMessageDialog(null, "Supplied Directory does not exist");
}
//display files on the TesxtField component
File[] filenames = f.listFiles();
String fn = Arrays.toString(filenames);
String type = f.isFile() ? "File" : "Directory : ";
long len = f.length();
String all = type +" "+" " + " Length: " + len;
dis.setText(all + "\n");
dis.setText(fn + "\n" + "\n" );
//Loops through the file and check sum of the list files
for(File file : f.listFiles()){
String hash;
try {
hash = MD5.asHex(MD5.getHash(file));
////////// Here is where my problems starts, Please help //////////
for(int i = 0; i < hash.length(); i++ )
for(int j = i + 1; j < hash.length(); j++){
File[] f1 = new File[i];
File[] f2 = new File[j];
boolean check = MD5.hashesEqual(MD5.getHash(new File(Arrays.toString(f1))),MD5.getHash(new File(Arrays.toString(f2)))); //compares the byte of files
System.out.println(check);
m.addElement(hash);
task.setModel(m);
}
}catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
For reading files in Java you need an InputStream object.
Look at this Question Getting a File's MD5 Checksum in Java which seems to help you with your problem
In my application I need to read a specific column of tab separated csv file using jsp. But I can read the data of full row not a specific column.
I need help this regard. Please help me
Thanks
mycode:
<%# page import="java.io.*"%>
<html>
<body>
<%
String fName = "c:\\csv\\myfile.csv";
String thisLine;
int count=0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
%>
<table>
<%
while ((thisLine = myInput.readLine()) != null)
{
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
if(i!=0)
{
out.print(" " +strar[j]+ " ");
}
else
{
out.print(" <b>" +strar[j]+ "</b> ");
}
}
out.println("<br>");
i++;
}
%>
</table>
</body>
</html>
I don't think you can read specific column.Better to read entire row using CSVParser or you can read CSV line by line and split it and get String array then you can get specific column but yes you need to read whole row gain.
Try it.
String fName = "C:\\Amit\\abc.csv";
String thisLine;
int count = 0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i = 0;
while ((thisLine = myInput.readLine()) != null) {
String strar[] = thisLine.split(",");
System.out.println(strar[3]);
// Here column 2
}
}
By this way you can read specific column.
I had a similar problem in Objective C the other day, but this is how I solved it.
This method assumes you know the column number of the data you want. (I.E. if you want column 1 of 6)
Read all the rows into strings and append them into one.
Data sample: (columns 1 to 6)
1,2,3,4,5,6
13,45,63,29,10,8
11,62,5,20,13,2
String 1 = 1,2,3,4,5,6
String 2 = 13,45,63,29,10,8
String 3 = 11,62,5,20,13,2
Then you should get this:
String combined = 1,2,3,4,5,6,13,45,63,29,10,8,11,62,5,20,13,2 //add in the missing "," when you concatenate strings
Next you need to split the string into an array of all values.
Use code somewhat like this: (written off the top of my head so may be off.)
String[] values = combined.split(",");
Now you should have something like this:
Values = `"1", "2", "3", ... etc`
The last step is to loop through the entire array and modulo for whatever column you need:
//Remember that java numbers arrays starting with 0.
//The key here is that all remainder 0 items fall into the first column. All remainder 1 items fall into the second column. And so on.
for(int i = 0; i < values.length(); i++)
{
//Column1 - Column6 -> array lists of size values.length/number of columns
//In this case they need to be size values.length/6
if(i % 6 == 0)
column1.add(values[i]);
else if(i % 6 == 1)
column2.add(values[i]);
else if(i % 6 == 2)
column3.add(values[i]);
else if(i % 6 == 3)
column4.add(values[i]);
else if(i % 6 == 4)
column5.add(values[i]);
else if(i % 6 == 5)
column6.add(values[i]);
}
~~~~~~~~~~~~~~~~
Edit:
You added code to your question. Above I was saving them into memory. You just loop through and print them out. In your while loop, split each line separately into an array and then either hardcode the column number or modulo the length of the array as the index.
public class ParseCSVs {
public static void main(String[] args) {
try {
// csv file containing data
String strFile = "./input//SIMNumbers.csv";
String line = "";
System.out.println("Enter line number to configure");
Scanner sc = new Scanner(System.in);
int lineNumber = sc.nextInt();
BufferedReader br = new BufferedReader(new FileReader(strFile));
if ((line = br.readLine()) != null) {
String cvsSplitBy = ",";
String blankCell = null;
// use comma as separator
String[] cols = line.split(cvsSplitBy);
for (int i = 0; i < cols.length; i++)
System.out.println("Coulmns = " + cols[i]);
// System.exit(0);
} else
System.out.println("No data found in csv");
} catch (IOException e) {
e.printStackTrace();
}
}
I have a similar problem.This is a snippet of my source:
FileWriter fstream = new FileWriter("results_for_excel.txt");
BufferedWriter writer = new BufferedWriter(fstream);
String sourceDirectory = "CVs";
File f = new File(sourceDirectory);
String[] filenames = f.list();
Arrays.sort(filenames);
String[] res = new String[filenames.length];
for (int i = 0; i < filenames.length; i++) {
System.out.println((i + 1) + " " + filenames[i]);
}
for (int i = 0; i < filenames.length; i++) {
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
res[i] = filenames[i].substring(beg,end);
System.out.println((i+1)+res[i]);
writer.write(res[i] + "\n");
}
writer.flush();
writer.close();
I get an exception at res[i] = filenames[i].substring(beg,end);
I cant figure what's going on.Thanks in advance:)
P.S I have read all the duplicates but nothing happened:(
Add the following code after
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
This will display the filename that is in the wrong format;
if (beg == -1 || end == -1)
{
System.out.println("Bad filename: " + filenames[i]);
}
The error occurs, because a filename does not contain both '-' and '.'. In that case indexOf returns -1 which is not a valid parameter for substring.
Either beg or end is -1. This means the filename doesn't contain - or .. Simple as that:)
Either
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
is returning a -1, its possible there's a file which doesn't contain either.
One of characters in this code
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
is not found, so either beg or end equals -1. That's why you got the exception while calling substring with negative arguments.
The problem was at a KDE file called ".directory".Thank you very very much all of you:)
I'm trying to write a method to take a multiline tab-delimited file and return the contents of that file as an arraylist of String arrays (each line is a String[], and each such String[] is an element of an arraylist). My problem is, I can't tell if the output is correct or not. I've printed each arraylist element and String[] element as they are saved to the arraylist, and those printings look correct. But after the arraylist is returned and I print the String[] in it, they appear to only have the contents of the very last line of the file. I'm suspecting it might be something about FileReader or BufferedReader that I don't know. Anyhoo, here's the code:
public class DataParsingTest {
static File AAPLDailyFile = new File("./textFilesForMethodTests/dataParsingPractice2.tsv");
public static void main(String[] args) throws FileNotFoundException, IOException {
ArrayList<String[]> stringArrayList = fileToStringArray(AAPLDailyFile);
System.out.println("stringArray.size() = " + stringArrayList.size());
System.out.println(stringArrayList.get(0)[0]);
for (int i = 0; i < stringArrayList.size(); i++) {
for (int j = 0; j < stringArrayList.get(i).length; j++) {
System.out.println("index of arraylist is " + i + " and element at index " + j + " of that array is " + stringArrayList.get(i)[j]);
}
}
}
public static ArrayList<String[]> fileToStringArray(File file) throws FileNotFoundException, IOException {
ArrayList<String[]> arrayListOfStringArrays = new ArrayList<String[]>();
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int nextChar = 0;
int noOfTokens = 1; // because the first token doesn't have a tab or newline before it
int startIndex = 0, endIndex = 0, tokenIndex = 0;
String toRead = "";
toRead = bufferedReader.readLine();
for (int i = 0; i < toRead.length(); i++) {
if (toRead.charAt(i) == '\t') {
noOfTokens++;
}
}
System.out.println("noOfTokens = " + noOfTokens);
bufferedReader.close();
fileReader.close();
String[] productString = new String[noOfTokens];
startIndex = 0;
endIndex = 0;
tokenIndex = 0;
FileReader fileReader2 = new FileReader(file);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
tokenIndex = 0;
int count = 1;
while ((toRead = bufferedReader2.readLine()) != null) {
System.out.println("toRead = " + toRead);
startIndex = -1; // [L - so that the first time an array element is assigned, it's upped to 0]
endIndex = 0;
tokenIndex = 0;
while (true) {
endIndex = toRead.indexOf("\t", startIndex + 1);
if (endIndex == -1) {
productString[tokenIndex] = toRead.substring(startIndex + 1);
System.out.println("tokenIndex = " + tokenIndex);
System.out.println("productString[" + tokenIndex + "] = " + productString[tokenIndex]);
tokenIndex++;
count++;
arrayListOfStringArrays.add(productString);
System.out.println("just added an array to the list. the first element is " + productString[0]);
break;
}
productString[tokenIndex] = toRead.substring(startIndex + 1, endIndex);
System.out.println("tokenIndex = " + tokenIndex);
System.out.println("productString[" + tokenIndex + "] = " + productString[tokenIndex]);
startIndex = endIndex;
tokenIndex++;
count++;
}
}
fileReader2.close();
bufferedReader2.close();
return arrayListOfStringArrays;
}
}
The input file is:
1 2
3 4
5 6
The output is:
noOfTokens = 2
toRead = 1 2
tokenIndex = 0
productString[0] = 1
tokenIndex = 1
productString[1] = 2
just added an array to the list. the first element is 1
toRead = 3 4
tokenIndex = 0
productString[0] = 3
tokenIndex = 1
productString[1] = 4
just added an array to the list. the first element is 3
toRead = 5 6
tokenIndex = 0
productString[0] = 5
tokenIndex = 1
productString[1] = 6
just added an array to the list. the first element is 5
stringArray.size() = 3
5 // from here on up, it looks like the method works correctly
index of arraylist is 0 and element at index 0 of that array is 5
index of arraylist is 0 and element at index 1 of that array is 6
index of arraylist is 1 and element at index 0 of that array is 5
index of arraylist is 1 and element at index 1 of that array is 6
index of arraylist is 2 and element at index 0 of that array is 5
index of arraylist is 2 and element at index 1 of that array is 6 //these 6 lines only reflect the last line of the input file.
Thanks a mil!
You're only creating a single string array, and reusing that for all lines. So your ArrayList just contains multiple references to the same object. You need to understand that when you call arrayListOfStringArrays.add(productString); that's not adding a copy of the array to the ArrayList - it's just adding a reference. (The value of productString is just a reference, not the array itself.)
Just move this:
String[] productString = new String[noOfTokens];
into the while loop, and all should be well. (In this respect, anyway. You should also be closing your file handles in finally blocks.)
That looks like too much code for me to process. Try this altered fileToStringArray method.
public static ArrayList<String[]> fileToStringArray(File file) throws FileNotFoundException, IOException {
ArrayList<String[]> returnVal = new ArrayList<String[]>();
// Scanner is a nifty utility for reading Files
Scanner fIn = new Scanner(file);
// keep reading while the Scanner has lines to process
while (fIn.hasNextLine()) {
// take the next line of the file, and split it up by each tab
// and add that String[] to the list
returnVal.add(fIn.nextLine().split("\t", -1));
}
return returnVal;
}