My code doesn't work correctly, I'm trying to decrypt a message but instead I get something like , 0, 3, ,, , 5, 7, <, ;, , ;, 9, ,, (, 4, , , -, ,, ), (, , �, ]
Please help me find where am I am wrong:
public class WorkInFile {
public static void main(String[] args) throws IOException {
FileInputStream encoded=new FileInputStream("C://Games//encoded.txt");//contains ƪÄÖØÐîÃÜÙäÌÊÛÓÕÒáÄßÕÍǨ³¾êÉàÝâÝãƒâÝäìÚÇäÖçÅáâÄÄÌØÐƭèÑØǑÚÚŲã¨
FileInputStream coded = new FileInputStream("C://Games//code.txt");//contains icbakwtbxxvcelsmjpbochqlltowxhlhvhyywsyqraargpdsycikmgeakonpiwcqmofwms
String text = encoded.toString();
String text2=coded.toString();
char[] chars=text.toCharArray();
char[] chars2=text2.toCharArray();
int index=0;
char[] res=new char[text.length()];
for (char aChar : chars) {
for (char c : chars2) {
res[index] = (char) (aChar - c);
}
index++;
}
String result= Arrays.toString(res);
System.out.println(result);
}
}
Files.readAllBytes(Paths.get("file-path"))
Java now offers a beautiful one-liner for reading file content.
Here is the working code for fetching file content as a string:
// WorkInFile.java
import java.nio.file.*;
public class WorkInFile {
public static void main(String[] args) {
try {
String text = new String(Files.readAllBytes(Paths.get("encoded.txt")));
System.out.println("Encoded.txt = " + text);
String text2 = new String(Files.readAllBytes(Paths.get("code.txt")));
System.out.println("code.txt = " + text2);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
If the expected message is in Japanese and it talks about Soviet data, this code is for you.
You must use a BufferedReader for read the file and a StringBuilder for build a String with what the BufferedReader extracts from the file.
public static void main(String args[]) {
String text;
String text2;
try {
Path encodedPath = Paths.get("C://Games//encoded.txt");
File encodedFile = new File(String.valueOf(encodedPath));
Path codedPath = Paths.get("C://Games//code.txt");
File codedFile = new File(String.valueOf(codedPath));
StringBuilder codedBuilder = new StringBuilder();
StringBuilder encodedBuilder = new StringBuilder();
try (
FileInputStream encoded = new FileInputStream(encodedFile.getAbsolutePath());
FileInputStream coded = new FileInputStream(codedFile.getAbsolutePath())
) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(coded))) {
String line;
while ((line = bufferedReader.readLine()) != null){
codedBuilder.append(line);
}
text = codedBuilder.toString();
}
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(encoded))){
String line;
while ((line = bufferedReader.readLine()) != null){
encodedBuilder.append(line);
}
text2 = encodedBuilder.toString();
}
char[] chars = text.toCharArray();
char[] chars2 = text2.toCharArray();
int index = 0;
char[] res = new char[text.length()];
for (char aChar : chars) {
for (char c : chars2) {
res[index] = (char) (aChar - c);
}
index++;
}
String result = Arrays.toString(res);
System.out.println(result);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
Let me know if that's what you wanted !
I think your problem lies out here:
String text = encoded.toString();
String text2=coded.toString();
You may refer to documentation to reach out that:
public String toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Returns:
a string representation of the object.
So, toString() returns the representation of FileInputStream not the content of the stream.
Related
How can I check if set of random characters from String of EditText matches a certain word from file?
For example:
EditText input: TINARSE
Can match word like NASTIER, STAINER.
Suppose a word in file is denoted by i.
I know how read strings from file just cant figure out how to match it with the random character input using IF statements.
Note: Length of string should be same as length EditText
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anagram=(EditText)findViewById(R.id.inputtext);
submit=(Button)findViewById(R.id.submit);
viewall=(TextView)findViewById(R.id.list);
viewall.setMovementMethod(new ScrollingMovementMethod());
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String a =anagram.getText().toString();
checkword("cswfifteen.txt",a);
}
});
}
private void checkword(String Filename, String a) {
StringBuilder builder = null;
BufferedReader reader = null;
ArrayList<String> words= new ArrayList<>();
try {
builder = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(
getAssets().open(Filename)
));
String Line;
while ((Line = reader.readLine()) != null) {
builder.append(Line).append("\n");
}
String[] dict = builder.toString().split("\n");
for (String i : dict) {
char[] b = i.toString().toCharArray();
Arrays.sort(b);
char[] c=a.replace("?","").toCharArray();
Arrays.sort(c);
if (String.valueOf(b).contains(String.valueOf(c)) && b.length==a.length()){
words.add(i);}
}
Collections.sort(words);
StringBuilder result = new StringBuilder();
for (String i : words)
{
result.append(i + "\n");
}
viewall.setText(result.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sort the text from EditText and word i from the file. Compare these two strings.
String textFromEditText= "zxbc";
String wordFromFile="cxbz";
char a[] = textFromEditText.toCharArray();
char c[] = wordFromFile.toCharArray();
Arrays.sort(a);
Arrays.sort(c);
System.out.println(String.valueOf(a).equalsIgnoreCase(String.valueOf(c)));
Use String.contains().
String name="what do you know about me";
if(name.contains("do you know"))
{
// do stuff
}
You can use extra attributes in conjunction with contains() like, trim() and equalsIgnoreCase().
for (String i : dict) {
char[] b = i.toString().toCharArray();
Arrays.sort(b);
char c[]=a.replace("?","").toCharArray();
Arrays.sort(c);
if (String.valueOf(b).contains(String.valueOf(c)) && b.length==a.length()) {
words.add(i);}
}
Collections.sort(words);
StringBuilder result = new StringBuilder();
for (String i : words)
{
result.append(i + "\n");
}
This is my code. it works good but is omitting some words that donot match the contains method. Example a sorted may be ?AEIRST where blank can be any letter from A to Z so it will ignore some words that after sorting their letters may contain a B or C or D on te 2nd index. how to counter that?
I have almost managed to accomplish this but not to the full. So what I need is for example I give the word DOG and the program will look into a text file and return DOG and GOD, i.e words that can be generated by the odds given only. My code is giving me all words that contain 'D', 'O' and 'G'. My code is this:
public class JavaReadTextFile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ReadFile rf = new ReadFile();
String filename = "/Users/Elton/Desktop/OSWI.txt";
String wordinput;
String wordarray[] = new String[1];
System.out.println("Input Characters: ");
wordinput = input.nextLine();
wordarray[0] = wordinput;
System.out.println(wordinput.length());
try {
String[] lines = rf.readLines(filename);
for (String line : lines) {
if (line.matches(wordarray[0] + ".*")) {
System.out.println(line);
}
}
} catch (IOException e) {
System.out.println("Unable to create " + filename + ": " + e.getMessage());
}
}
}
----- then i have:
public class ReadFile {
String [] cName = new String [100];
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null ) {
cName[0] = line.split(" ")[0];
lines.add(cName[0]);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
I can see you are able to read the words from file. Rest of the work is simple. algorithm will be something like this
sort inputWord
sort the word you read from file
if both word is same print or add it to some list.
And here is simple demonstration of above algorithm you can modify it to your need.
public class App {
static String sortString (String str) {
char []chars = str.toCharArray();
sort(chars);
return new String(chars);
}
public static void main(String... args) {
String inputWord = "DoG";
String readWord = "God";
inputWord = inputWord.toUpperCase();
readWord = readWord.toUpperCase();
inputWord = sortString(inputWord);
readWord = sortString(readWord);
if(inputWord.equalsIgnoreCase(readWord)) {
System.out.println(readWord);// you can add it to your list
}
}
}
If I understand you correctly, you want to display all the anagrams of a word?
Change your method readLines() to return an ArrayList instead of an array.
ArrayList<String> readLines(String fname) {
File file = new File(fname);
ArrayList<String> list = null;
try {
Scanner scanner = new Scanner(file);
list = new ArrayList<String>();
while (scanner.hasNext()) {
String currentWord = scanner.next();
if (!currentWord.isEmpty()) {
list.add(currentWord);
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return list;
}
The use this function with input parameter dictionary being the ArrayList you return from readLines. The function uses the fact that two anagrams like "DOG" and "GOD" are equal strings when both are sorted (i.e. "DGO" equals "DGO")
public ArrayList<String> getAnagrams(String word, ArrayList<String> dictionary) {
if(word == null || dictionary == null) {
return null;
}
ArrayList<String> anagrams = new ArrayList<String>();
char[] sortedChars = word.toCharArray();
Arrays.sort(sortedChars);
for(String item : dictionary) {
char[] sortedDictionaryItem = item.toCharArray();
Arrays.sort(sortedDictionaryItem);
if(Arrays.equals(sortedChars, sortedDictionaryItem)) {
anagrams.add(item);
}
}
return anagrams;
}
If you don't like the changes I am suggesting, you can also do the following. In the loop where you do:
if (line.matches(wordarray[0] + ".*")) {
System.out.println(line);
}
You can check if the two strings are permutations of each other:
if (isPermutation(line, wordarray[0]) {
System.out.println(line);
}
By adding these two functions:
String sortString(String s) {
char[] chars = s.toCharArray();
java.util.Arrays.sort(chars);
return new String(chars);
}
boolean isPermutation(String s1, String s2) {
if(s1.length() != s2.length()) {
return false;
}
s1 = sortString(s1);
s2 = sortString(s2);
return (s1.compareTo(s2) == 0);
}
This may help you adapt your code.
import java.util.regex.* ;
public class Find_Dogs_And_Gods
{
public static void main(String []args)
{
String line = "2ldoghmDoggod" ;
Pattern p = Pattern.compile("[d,D,g,G][o,O][d,D,g,G]") ;
Matcher m = p.matcher(line) ;
while(m.find() )
{
System.out.println( m.group() ) ;
}
}
}
I have a large text file. I want to put every character in the text file, in to Character array. I use this code to put it.
List<String> set = new ArrayList<String>();
BufferedReader bf = new BufferedReader(new FileReader(file_path));
String check_line=bf.readLine();
while(check_line!=null){
set.add(check_line);
check_line=bf.readLine();
}
ArrayList<Character> charr = new ArrayList<Character>();
for(int j=0;j<set.size();++j){
String str=set.get(j);
for (int x = 0; x < str.length(); x ++){
charr.add(str.charAt(x));
}}
return charr;
But it takes long time.Is there any efficient way to do this?
You can use for each line
char[] x = str.toCharArray();
With Java 8:
public static void main(final String[] args) throws IOException {
final Path file = Paths.get("path", "to", "file");
final Character[] characters = toCharacters(file);
}
public static Character[] toCharacters(final Path file) throws IOException {
try (final Stream<String> lines = Files.lines(file)) {
return lines.flatMapToInt(String::chars).
mapToObj(x -> (char) x).
toArray(Character[]::new);
}
}
More efficient coding wise, and fewer intermediate collections created. Not sure it will be much faster however as this involves file IO which is very slow.
Why do you use a list of Strings as a temp variable and don't directly store to your Character List?
ArrayList<Character> charr = new ArrayList<Character>();
String check_line=bf.readLine();
while(check_line!=null){
for(char c : check_line.toCharArray())
charr.add(c);
check_line=bf.readLine();
}
return charr;
Just concatenate the line into one string and then convert them to an char array.
public char[] extractCharArray(String fileName) {
char[] charArray = null;
try(BufferedReader bf = new BufferedReader(new FileReader(fileName))) {
StringBuilder completeFileString = new StringBuilder();
String check_line=bf.readLine();
while(check_line!=null){
completeFileString = completeFileString.append(check_line);
check_line=bf.readLine();
}
charArray = completeFileString.toString().toCharArray();
} catch(IOException ex) {
//Handle the exception
}
return charArray;
}
I'm extracting 5 webpages using bufferedreader, each separated by a space, I want to use a substring to extract each pages url, html, source, and date. But I need guidance on how to use the substring properly to achieve this, cheers.
public static List<WebPage> readRawTextFile(Context ctx, int resId) {
InputStream inputStream = ctx.getResources().openRawResource(
R.raw.pages);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = buffreader.readLine()) != null) {
if (line.length() == 0) {
// ignore for now
//Will be used when blank line is encountered
}
if (line.length() != 0) {
//here I want the substring to pull out the correctStrings
int sURL = line.indexOf("<!--");
int eURL = line.indexOf("-->");
line.substring(sURL,eURL);
**//Problem is here**
}
}
} catch (IOException e) {
return null;
}
return null;
}
I think what u want is like this ,
public class Test {
public static void main(String args[]) {
String text = "<!--Address:google.co.uk.html-->";
String converted1 = text.replaceAll("\\<!--", "");
String converted2 = converted1.replaceAll("\\-->", "");
System.out.println(converted2);
}
}
result show : Address:google.co.uk.html
In catch block don't return null, use printStackTrace();. It will help you to find if something went wrong.
String str1 = "<!--Address:google.co.uk.html-->";
// Approach 1
int st = str1.indexOf("<!--"); // gives index which starts from <
int en = str1.indexOf("-->"); // gives index which starts from -
str1 = str1.substring(st + 4, en);
System.out.println(str1);
// Approach 2
String str2 = "<!--Address:google.co.uk.html-->";
str2 = str2.replaceAll("[<>!-]", "");
System.out.println( str2);
Note $100: be aware that using regex in replaceAll it will replace everything in string containing regex params.
I have this code to sort a text file using arrays in java, but it always discard the first line of the text while sorting.
Here is my code:
import java.io.*;
public class Main {
public static int count(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return count;
} finally {
is.close();
}
}
public static String[] getContents(File aFile) throws IOException {
String[] words = new String[count(aFile.getName()) + 1];
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
int i = 0;
while ((line = input.readLine()) != null) {
words[i] = line;
i++;
}
java.util.Arrays.sort(words);
for (int k = 0; k < words.length; k++) {
System.out.println(words[k]);
}
return words;
}
public static void main(String[] args) throws IOException {
File testFile = new File("try.txt");
getContents(testFile);
}
}
Here is the text file try.txt:
Daisy
Jane
Amanda
Barbara
Alexandra
Ezabile
the output is:
Alexandra
Amanda
Barbara
Ezabile
Jane
Daisy
To solve this problem I have to insert an empty line in the beginning of the text file, is there a way not to do that? I don't know what goes wrong?
I compiled your code (on a Mac) and it works for me. Try opening the file in a hexeditor and see if there is some special character at the beginning of your file. That might be causing the sorting to be incorrect for the first line.
You probably have a BOM (Byte Order Marker) at the beginning at the file. By definition they will be interpreted as zero-width non-breaking-space.
So if you have
String textA = new String(new byte[] { (byte)0xef, (byte)0xbb, (byte) 0xbf, 65}, "UTF-8");
String textB = new String(new byte[] { 66}, "UTF-8");
System.err.println(textA + " < " + textB + " = " + (textA.compareTo(textB) < 0));
The character should show up in your length of the strings, so try printing the length of each line.
System.out.println(words[k] + " " + words[k].length());
And use a list or some other structure so you don't have to read the file twice.
Try something simpler, like this:
public static String[] getContents(File aFile) throws IOException {
List<String> words = new ArrayList<String>();
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line;
while ((line = input.readLine()) != null)
words.add(line);
Collections.sort(words);
return words.toArray(new String[words.size()]);
}
public static void main(String[] args) throws IOException {
File testFile = new File("try.txt");
String[] contents = getContents(testFile);
for (int k = 0; k < contents.length; k++) {
System.out.println(contents[k]);
}
}
Notice that you don't have to iterate over the file to determine how many lines it has, instead I'm adding the lines to an ArrayList, and at the end, converting it to an array.
Use List and the add() method to read your file contents.
Then use Collections.sort() to sort the List.