CharBuffer.put() didn't working - java

I try to put some strings to CharBuffer with CharBuffer.put() function
but the buffer is left blank.
my code:
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
System.out.println(charBuf);
I tried to use with clear() or rewind() after allocate(1000) but that did not change the result.

Try this:
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);
The detail you're missing is that writing moves the current pointer to the end of the written data, so when you're printing it out, it's starting at the current pointer, which has nothing written.

Add a call to rewind() right after the loop.

You will need to flip() the buffer before you can read from the buffer. The flip() method needs to be called before reading the data from the buffer. When the flip() method is called the limit is set to the current position, and the position to 0. e.g.
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.flip();
System.out.println(charBuf);
The above will only print the characters in the buffers and not the unwritten space in the buffer.

You must rewind it after you put in the objects, try this
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);

Related

Cannot access the value of a StringBuilder in a heap dump in VisualVM

I am willing to write the value of a large StringBuilder with index 827 to disk. I am trying to do that using the following OQL:
map(heap.objects('java.lang.StringBuilder'),
function(it, index) {
if (index == 827.0) {
var writer = new java.io.FileWriter("/Users/username/output/sb_0x" + it.id.toString(16) + ".txt");
var chars = it.value;
for (var i = 0; i < chars.length; i++) {
writer.write(chars[i]);
}
writer.close();
}
return index;
})
However, nothing gets written. I now that the builder exists, since I have inspected it:
All StringBuilder objects
It seems that the result gets truncated after the builder with index 99 (i.e. it works for 99, but doesn't work for 100):
Truncated after 100
Any suggestions how can I get the value of the StringBuilder with id 827?
You can use the following query:
filter(heap.objects('java.lang.StringBuilder'),
function(it, index) {
if (index == 827.0) {
var writer = new java.io.FileWriter("/Users/username/output/sb_0x" + it.id.toString(16) + ".txt");
var chars = it.value;
for (var i = 0; i < chars.length; i++) {
writer.write(chars[i]);
}
writer.close();
return true;
}
return false;
})

How Add Strings from Multiple Text Files to Array

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);

store 1d array from text file java

Am I reading the following input correctly?
Here is my code so far:
while ((line = br.readLine()) != null) {
line = line.substring(line.indexOf('[')+1, line.indexOf(']'));
String[] parts = line.split(",");
for (int i = 0; i< parts.length; i++) {
rangeNo[i]= Integer.parseInt(parts[i]);
System.out.println("{" + rangeNo[i] + "}");
}
}
and this is my input
[2,9], [3,11]
Also, when I try to print the value of rangeNo[3] it return 0 instead of 3
can someone help me out with this?
Do you expect [2,9], [3,11] to be in one line or two separate lines?
If its supposed to be one line then you might want to try something like this
Integer rangeNo[] = new Integer[10];
String line = "[2,9], [3,11]";
line = line.replace('[', ' ');
line = line.replace(']', ' ');
String[] parts = line.split(",");
for (int i = 0; i < parts.length; i++) {
rangeNo[i] = Integer.parseInt(parts[i].trim());
System.out.println("{" + rangeNo[i] + "}");
}
when you check here
line = line.substring(line.indexOf('[')+1, line.indexOf(']'));
it's matching first condition. i.e works fine for [2,9] not after that thus only 2 and 9 are getting stored here.
String[] parts = line.split(",");
so
parts[0]=2
parts[1]=9
parts[2]=0

Iterate through and show the values in a 2D array taken from a text file

Hi I am new to 2D arrays and I am having problems with showing the content of the array indexes. I am reading the values from a text file and storing them into a 2D array. I am not sure if the items are even storing properly. When I use a System.println() during the iteration of the 2D array being filled then it prints all the values out as they currently show up. However if I try filling the array and call any location index after such as data[45][45]; it will only return a 0. Each int value taken from the text file that should be stored are each in the millions.
final String FILENAME = "DATA.TXT";
int [ ][ ] data = null;
int numberOfRows = 0;
int numberOfCols = 0;
String message ="";
try {
File file = new File(FILENAME);
Scanner inputFile = new Scanner(file);
// Read the number of Rows and Columns first
numberOfRows = inputFile.nextInt();
numberOfCols = inputFile.nextInt();
//Creates the row and column amount
data = new int[numberOfRows][numberOfCols];
for(int i = 0; i < data.length; i++)
{
for(int j = 0; j < data[5].length; j++)
{
while(inputFile.hasNextInt())
{
data[i][j] = inputFile.nextInt();
//System.out.println(data[i][j]); //This works for displaying the values cuurently
}
}
}
inputFile.close();
}
catch (FileNotFoundException ex)
{
System.out.println("Error reading data from " + FILENAME +
" Exception = " + ex.getMessage());
}
System.out.println("Data has been read - file has " + numberOfRows +
" rows and " + numberOfCols + " columns.");
//THIS or even using a loop to iterate through the 2D array that should contain
// the values does not appear and only ends up as 0 as if the values are not stored.
System.out.print(data[56][56]);
}
}
I have looked at this for a few hours and I do not understand if the values are not being stored properly or if there is a reason I cannot call the value in any index of data such as data[45][45] or using a loop such as
for(int n =0; n <data.length; n++)
{
for(int k = 0; k < data[0].length; k++)
{
System.out.print(data[n][k]);
}
}
If I am doing this completely wrong or there is a much more efficient way to do this please let me know. Otherwise in general I do not know what is wrong.
Thank you for checking out my post and I believe this would be helpful to many new programmers to 2D arrays and file read.
FILE CONTENTS
500 1000
1052662 1025260 1064342 1045596 1093363 1063663 1014129 1070544 1005352 1046317 1059536 1009817 1049327 1012134 1047499 1026392 1056558 1098823 1060554 1028017 1046977 1022098 1018538 1077771 1082687 1025653 1056869 1076473 1097420 1080444 1063797 1014295 1083251 1037760 1026325 1003914 1034680 1069524 1029877 1075546 1047177 1061381 1080359 1035442
Try this :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final String FILENAME = "d:/data.txt";
long[][] data=null;
int numberOfRows = 0;
int numberOfCols = 0;
String message = "";
try {
File file = new File(FILENAME);
Scanner inputFile = new Scanner(file);
// Read the number of Rows and Columns first
numberOfRows = inputFile.nextInt();
numberOfCols = inputFile.nextInt();
// Creates the row and column amount
data = new long[numberOfRows][numberOfCols];
for (int i = 0; i < numberOfRows; i++) {
for (int j = 0; j < numberOfCols; j++) {
data[i][j] = inputFile.nextInt();
}
}
inputFile.close();
} catch (FileNotFoundException ex) {
System.out.println("Error reading data from " + FILENAME
+ " Exception = " + ex.getMessage());
}
System.out.println("Data has been read - file has " + numberOfRows
+ " rows and " + numberOfCols + " columns.");
// display 2D array
for(int n =0; n <numberOfRows; n++)
{
for(int k = 0; k < numberOfCols; k++)
{
System.out.print(data[n][k] +" ");
}
System.out.println();
}
}
}
Found out I just had to get rid of the while statement and it seems to work perfectly. Thanks for all your help tho.

String index out of range: -1

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:)

Categories