从资产文件夹中获取随机一行文本。

huangapple go评论115阅读模式
英文:

Get a random line from a text file in assets folder

问题

以下是翻译好的部分:

  1. package com.bechrisapps.passworder;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.content.ClipData;
  4. import android.content.ClipboardManager;
  5. import android.content.Context;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.TextView;
  10. import com.bechrisapps.passworder.utility.FileUtil;
  11. import java.util.ArrayList;
  12. import java.util.HashMap;
  13. import org.jetbrains.annotations.NotNull;
  14. public class GeneratedActivity extends AppCompatActivity {
  15. public static int MINIMAL_LENGTH = 1;
  16. public static String CHARACTER_IN_BETWEEN = "";
  17. public static ArrayList<HashMap<String, Object>> REPLACEMENT_RULE = MainActivity.replacementRule;
  18. private String replaceFrom = "", replaceTo = "";
  19. private TextView textView;
  20. private Button btnGenerate, btnCopy;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_generated);
  25. initialize();
  26. initializeLogic();
  27. }
  28. private void initialize() {
  29. textView = findViewById(R.id.generated_password);
  30. btnGenerate = findViewById(R.id.generated_renew);
  31. btnCopy = findViewById(R.id.generated_copy);
  32. btnCopy.setOnClickListener(new View.OnClickListener() {
  33. @Override
  34. public void onClick(View v) {
  35. ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
  36. ClipData clip = ClipData.newPlainText("copiedPassword", textView.getText().toString());
  37. clipboardManager.setPrimaryClip(clip);
  38. }
  39. });
  40. }
  41. private void initializeLogic() {
  42. generatePassword(MINIMAL_LENGTH, CHARACTER_IN_BETWEEN, REPLACEMENT_RULE);
  43. }
  44. private String generatePassword(int minLength, String charactersInBetween, @NotNull ArrayList<HashMap<String, Object>> replacementRule) {
  45. String wordList = FileUtil.readFile(getAssets() + "WordList.txt");
  46. String output = "";
  47. for (int i = 0; i < replacementRule.size(); i++) {
  48. output = output.replaceAll(replacementRule.get(i).get("replaceFrom").toString(), replacementRule.get(i).get("replaceTo").toString());
  49. }
  50. return output;
  51. }
  52. }
  1. package com.bechrisapps.passworder.utility;
  2. import android.content.ContentResolver;
  3. import android.content.Context;
  4. import android.database.Cursor;
  5. import android.net.Uri;
  6. import android.os.Environment;
  7. import android.provider.DocumentsContract;
  8. import android.provider.MediaStore;
  9. import android.text.TextUtils;
  10. import android.util.Log;
  11. import java.io.*;
  12. import java.net.URLDecoder;
  13. import java.util.ArrayList;
  14. import java.util.zip.ZipEntry;
  15. import java.util.zip.ZipInputStream;
  16. import java.util.zip.ZipOutputStream;
  17. public class FileUtil {
  18. private static void createNewFile(String path) {
  19. int lastSep = path.lastIndexOf(File.separator);
  20. if (lastSep > 0) {
  21. String dirPath = path.substring(0, lastSep);
  22. makeDir(dirPath);
  23. }
  24. File file = new File(path);
  25. try {
  26. if (!file.exists())
  27. file.createNewFile();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. public static String readFile(String path) {
  33. createNewFile(path);
  34. StringBuilder sb = new StringBuilder();
  35. FileReader fr = null;
  36. try {
  37. fr = new FileReader(new File(path));
  38. char[] buff = new char[1024];
  39. int length = 0;
  40. while ((length = fr.read(buff)) > 0) {
  41. sb.append(new String(buff, 0, length));
  42. }
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. } finally {
  46. if (fr != null) {
  47. try {
  48. fr.close();
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }
  54. return sb.toString();
  55. }
  56. public static void writeFile(String path, String str) {
  57. createNewFile(path);
  58. FileWriter fileWriter = null;
  59. try {
  60. fileWriter = new FileWriter(new File(path), false);
  61. fileWriter.write(str);
  62. fileWriter.flush();
  63. } catch (IOException e) {
  64. e.printStackTrace();
  65. } finally {
  66. try {
  67. if (fileWriter != null)
  68. fileWriter.close();
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. }
  74. // ...
  75. // (此处省略了其他方法内容)
  76. // ...
  77. }

请注意,为了保持可读性,我省略了一些代码的部分,只保留了核心内容。如果需要完整的代码,请确保将原始代码复制粘贴到适当的开发环境中。

英文:

I am currently trying to re-create a project from Python into Android Application. But I am currently stuck with something I don't literally know.

My Project is called "Passworder" (for generating German Passwords). And to make the password to generate NOT random letters, I want to generate words from "WordList.txt" from assets folder.

The Problem is, that I don't even know, how to generate random words. With minimalLength and replacementRule, then I can do it.

Some code from my void:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. // GeneratedActivity
  2. private String generatePassword(int minLength, String charactersInBetween, @org.jetbrains.annotations.NotNull ArrayList&lt;HashMap&lt;String, Object&gt;&gt; replacementRule) {
  3. String wordList = FileUtil.readFile(getAssets() + &quot;WordList.txt&quot;);
  4. String output = &quot;&quot;;
  5. for (int i = 0; i &lt; replacementRule.size(); i++) {
  6. output = output.replaceAll(replacementRule.get(i).get(&quot;replaceFrom&quot;).toString(), replacementRule.get(i).get(&quot;replaceTo&quot;).toString());
  7. }
  8. return output;
  9. }
  10. // FileUtil.readFile(String path)
  11. public static String readFile(String path) {
  12. createNewFile(path);
  13. StringBuilder sb = new StringBuilder();
  14. FileReader fr = null;
  15. try {
  16. fr = new FileReader(new File(path));
  17. char[] buff = new char[1024];
  18. int length = 0;
  19. while ((length = fr.read(buff)) &gt; 0) {
  20. sb.append(new String(buff, 0, length));
  21. }
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. } finally {
  25. if (fr != null) {
  26. try {
  27. fr.close();
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33. return sb.toString();
  34. }

<!-- end snippet -->

Yes, that code is even from that application "Sketchware"

<hr>

EDIT (of my full GeneratedActivity.java)

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. package com.bechrisapps.passworder;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.content.ClipData;
  4. import android.content.ClipboardManager;
  5. import android.content.Context;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.TextView;
  10. import com.bechrisapps.passworder.utility.FileUtil;
  11. import java.util.ArrayList;
  12. import java.util.HashMap;
  13. import org.jetbrains.annotations.NotNull;
  14. public class GeneratedActivity extends AppCompatActivity {
  15. public static int MINIMAL_LENGTH = 1;
  16. public static String CHARACTER_IN_BETWEEN = &quot;&quot;;
  17. public static ArrayList&lt;HashMap&lt;String, Object&gt;&gt; REPLACEMENT_RULE = MainActivity.replacementRule;
  18. private String replaceFrom = &quot;&quot;, replaceTo = &quot;&quot;;
  19. private TextView textView;
  20. private Button btnGenerate, btnCopy;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_generated);
  25. initialize();
  26. initializeLogic();
  27. }
  28. private void initialize() {
  29. textView = findViewById(R.id.generated_password);
  30. btnGenerate = findViewById(R.id.generated_renew);
  31. btnCopy = findViewById(R.id.generated_copy);
  32. btnCopy.setOnClickListener(new View.OnClickListener() {
  33. @Override
  34. public void onClick(View v) {
  35. ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
  36. ClipData clip = ClipData.newPlainText(&quot;copiedPassword&quot;, textView.getText().toString());
  37. clipboardManager.setPrimaryClip(clip);
  38. }
  39. });
  40. }
  41. private void initializeLogic() {
  42. generatePassword(MINIMAL_LENGTH, CHARACTER_IN_BETWEEN, REPLACEMENT_RULE);
  43. }
  44. private String generatePassword(int minLength, String charactersInBetween, @NotNull ArrayList&lt;HashMap&lt;String, Object&gt;&gt; replacementRule) {
  45. String wordList = FileUtil.readFile(getAssets() + &quot;WordList.txt&quot;);
  46. String output = &quot;&quot;;
  47. for (int i = 0; i &lt; replacementRule.size(); i++) {
  48. output = output.replaceAll(replacementRule.get(i).get(&quot;replaceFrom&quot;).toString(), replacementRule.get(i).get(&quot;replaceTo&quot;).toString());
  49. }
  50. return output;
  51. }
  52. }

<!-- end snippet -->

<hr>

FileUtil.java

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. package com.bechrisapps.passworder.utility;
  2. import android.content.ContentResolver;
  3. import android.content.ContentUris;
  4. import android.content.Context;
  5. import android.database.Cursor;
  6. import android.graphics.Bitmap;
  7. import android.graphics.BitmapFactory;
  8. import android.graphics.Canvas;
  9. import android.graphics.ColorFilter;
  10. import android.graphics.ColorMatrix;
  11. import android.graphics.ColorMatrixColorFilter;
  12. import android.graphics.LightingColorFilter;
  13. import android.graphics.Matrix;
  14. import android.graphics.Paint;
  15. import android.graphics.PorterDuff;
  16. import android.graphics.PorterDuffXfermode;
  17. import android.graphics.Rect;
  18. import android.graphics.RectF;
  19. import android.media.ExifInterface;
  20. import android.net.Uri;
  21. import android.os.Environment;
  22. import android.provider.DocumentsContract;
  23. import android.provider.MediaStore;
  24. import android.text.TextUtils;
  25. import android.util.Log;
  26. import java.io.BufferedInputStream;
  27. import java.io.BufferedOutputStream;
  28. import java.io.File;
  29. import java.io.FileInputStream;
  30. import java.io.FileNotFoundException;
  31. import java.io.FileOutputStream;
  32. import java.io.FileReader;
  33. import java.io.FileWriter;
  34. import java.io.IOException;
  35. import java.net.URLDecoder;
  36. import java.text.SimpleDateFormat;
  37. import java.util.ArrayList;
  38. import java.util.Date;
  39. import java.util.zip.ZipEntry;
  40. import java.util.zip.ZipInputStream;
  41. import java.util.zip.ZipOutputStream;
  42. public class FileUtil {
  43. private static void createNewFile(String path) {
  44. int lastSep = path.lastIndexOf(File.separator);
  45. if (lastSep &gt; 0) {
  46. String dirPath = path.substring(0, lastSep);
  47. makeDir(dirPath);
  48. }
  49. File file = new File(path);
  50. try {
  51. if (!file.exists())
  52. file.createNewFile();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. public static String readFile(String path) {
  58. createNewFile(path);
  59. StringBuilder sb = new StringBuilder();
  60. FileReader fr = null;
  61. try {
  62. fr = new FileReader(new File(path));
  63. char[] buff = new char[1024];
  64. int length = 0;
  65. while ((length = fr.read(buff)) &gt; 0) {
  66. sb.append(new String(buff, 0, length));
  67. }
  68. } catch (IOException e) {
  69. e.printStackTrace();
  70. } finally {
  71. if (fr != null) {
  72. try {
  73. fr.close();
  74. } catch (Exception e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. }
  79. return sb.toString();
  80. }
  81. public static void writeFile(String path, String str) {
  82. createNewFile(path);
  83. FileWriter fileWriter = null;
  84. try {
  85. fileWriter = new FileWriter(new File(path), false);
  86. fileWriter.write(str);
  87. fileWriter.flush();
  88. } catch (IOException e) {
  89. e.printStackTrace();
  90. } finally {
  91. try {
  92. if (fileWriter != null)
  93. fileWriter.close();
  94. } catch (IOException e) {
  95. e.printStackTrace();
  96. }
  97. }
  98. }
  99. public static void copyFile(String sourcePath, String destPath) {
  100. if (!isExistFile(sourcePath)) return;
  101. createNewFile(destPath);
  102. FileInputStream fis = null;
  103. FileOutputStream fos = null;
  104. try {
  105. fis = new FileInputStream(sourcePath);
  106. fos = new FileOutputStream(destPath, false);
  107. byte[] buff = new byte[1024];
  108. int length = 0;
  109. while ((length = fis.read(buff)) &gt; 0) {
  110. fos.write(buff, 0, length);
  111. }
  112. } catch (IOException e) {
  113. e.printStackTrace();
  114. } finally {
  115. if (fis != null) {
  116. try {
  117. fis.close();
  118. } catch (IOException e) {
  119. e.printStackTrace();
  120. }
  121. }
  122. if (fos != null) {
  123. try {
  124. fos.close();
  125. } catch (IOException e) {
  126. e.printStackTrace();
  127. }
  128. }
  129. }
  130. }
  131. public static void moveFile(String sourcePath, String destPath) {
  132. copyFile(sourcePath, destPath);
  133. deleteFile(sourcePath);
  134. }
  135. public static void deleteFile(String path) {
  136. File file = new File(path);
  137. if (!file.exists()) return;
  138. if (file.isFile()) {
  139. file.delete();
  140. return;
  141. }
  142. File[] fileArr = file.listFiles();
  143. if (fileArr != null) {
  144. for (File subFile : fileArr) {
  145. if (subFile.isDirectory()) {
  146. deleteFile(subFile.getAbsolutePath());
  147. }
  148. if (subFile.isFile()) {
  149. subFile.delete();
  150. }
  151. }
  152. }
  153. file.delete();
  154. }
  155. public static boolean isExistFile(String path) {
  156. File file = new File(path);
  157. return file.exists();
  158. }
  159. public static void makeDir(String path) {
  160. if (!isExistFile(path)) {
  161. File file = new File(path);
  162. file.mkdirs();
  163. }
  164. }
  165. public static void listDir(String path, ArrayList&lt;String&gt; list) {
  166. File dir = new File(path);
  167. if (!dir.exists() || dir.isFile()) return;
  168. File[] listFiles = dir.listFiles();
  169. if (listFiles == null || listFiles.length &lt;= 0) return;
  170. if (list == null) return;
  171. list.clear();
  172. for (File file : listFiles) {
  173. list.add(file.getAbsolutePath());
  174. }
  175. }
  176. public static boolean isDirectory(String path) {
  177. if (!isExistFile(path)) return false;
  178. return new File(path).isDirectory();
  179. }
  180. public static boolean isFile(String path) {
  181. if (!isExistFile(path)) return false;
  182. return new File(path).isFile();
  183. }
  184. public static long getFileLength(String path) {
  185. if (!isExistFile(path)) return 0;
  186. return new File(path).length();
  187. }
  188. public static String getExternalStorageDir() {
  189. return Environment.getExternalStorageDirectory().getAbsolutePath();
  190. }
  191. public static String getPackageDataDir(Context context) {
  192. return context.getExternalFilesDir(null).getAbsolutePath();
  193. }
  194. public static String getPackageObbDir() {
  195. return FileUtil.getExternalStorageDir() + &quot;/Android/obb/com.theblacklistedgame.blacklisted&quot;;
  196. }
  197. public static String getPublicDir(String type) {
  198. return Environment.getExternalStoragePublicDirectory(type).getAbsolutePath();
  199. }
  200. public static String convertUriToFilePath(final Context context, final Uri uri) {
  201. String path = null;
  202. if (DocumentsContract.isDocumentUri(context, uri)) {
  203. if (isExternalStorageDocument(uri)) {
  204. final String docId = DocumentsContract.getDocumentId(uri);
  205. final String[] split = docId.split(&quot;:&quot;);
  206. final String type = split[0];
  207. if (&quot;primary&quot;.equalsIgnoreCase(type)) {
  208. path = Environment.getExternalStorageDirectory() + &quot;/&quot; + split[1];
  209. }
  210. } else if (isDownloadsDocument(uri)) {
  211. final String id = DocumentsContract.getDocumentId(uri);
  212. if (!TextUtils.isEmpty(id)) {
  213. if (id.startsWith(&quot;raw:&quot;)) {
  214. return id.replaceFirst(&quot;raw:&quot;, &quot;&quot;);
  215. }
  216. }
  217. final Uri contentUri = ContentUris
  218. .withAppendedId(Uri.parse(&quot;content://downloads/public_downloads&quot;), Long.valueOf(id));
  219. path = getDataColumn(context, contentUri, null, null);
  220. } else if (isMediaDocument(uri)) {
  221. final String docId = DocumentsContract.getDocumentId(uri);
  222. final String[] split = docId.split(&quot;:&quot;);
  223. final String type = split[0];
  224. Uri contentUri = null;
  225. if (&quot;image&quot;.equals(type)) {
  226. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  227. } else if (&quot;video&quot;.equals(type)) {
  228. contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  229. } else if (&quot;audio&quot;.equals(type)) {
  230. contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  231. }
  232. final String selection = MediaStore.Audio.Media._ID + &quot;=?&quot;;
  233. final String[] selectionArgs = new String[]{
  234. split[1]
  235. };
  236. path = getDataColumn(context, contentUri, selection, selectionArgs);
  237. }
  238. } else if (ContentResolver.SCHEME_CONTENT.equalsIgnoreCase(uri.getScheme())) {
  239. path = getDataColumn(context, uri, null, null);
  240. } else if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(uri.getScheme())) {
  241. path = uri.getPath();
  242. }
  243. if (path != null) {
  244. try {
  245. return URLDecoder.decode(path, &quot;UTF-8&quot;);
  246. } catch (Exception e) {
  247. return null;
  248. }
  249. }
  250. return null;
  251. }
  252. private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
  253. Cursor cursor = null;
  254. final String column = MediaStore.Images.Media.DATA;
  255. final String[] projection = {
  256. column
  257. };
  258. try {
  259. cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
  260. if (cursor != null &amp;&amp; cursor.moveToFirst()) {
  261. final int column_index = cursor.getColumnIndexOrThrow(column);
  262. return cursor.getString(column_index);
  263. }
  264. } catch (Exception e) {
  265. } finally {
  266. if (cursor != null) {
  267. cursor.close();
  268. }
  269. }
  270. return null;
  271. }
  272. private static boolean isExternalStorageDocument(Uri uri) {
  273. return &quot;com.android.externalstorage.documents&quot;.equals(uri.getAuthority());
  274. }
  275. private static boolean isDownloadsDocument(Uri uri) {
  276. return &quot;com.android.providers.downloads.documents&quot;.equals(uri.getAuthority());
  277. }
  278. private static boolean isMediaDocument(Uri uri) {
  279. return &quot;com.android.providers.media.documents&quot;.equals(uri.getAuthority());
  280. }
  281. private static final int BUFFER_SIZE = 8192;
  282. private static String TAG = FileUtil.class.getName();
  283. private static String parentPath = &quot;&quot;;
  284. public static boolean zip(String sourcePath, String destinationPath, String destinationFileName, Boolean includeParentFolder) {
  285. new File(destinationPath).mkdirs();
  286. FileOutputStream fileOutputStream;
  287. ZipOutputStream zipOutputStream = null;
  288. try {
  289. if (!destinationPath.endsWith(&quot;/&quot;)) destinationPath += &quot;/&quot;;
  290. String destination = destinationPath + destinationFileName;
  291. File file = new File(destination);
  292. if (!file.exists()) file.createNewFile();
  293. fileOutputStream = new FileOutputStream(file);
  294. zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
  295. if (includeParentFolder)
  296. parentPath = new File(sourcePath).getParent() + &quot;/&quot;;
  297. else
  298. parentPath = sourcePath;
  299. zipFile(zipOutputStream, sourcePath);
  300. } catch (IOException ioe) {
  301. Log.d(TAG, ioe.getMessage());
  302. return false;
  303. } finally {
  304. if (zipOutputStream != null)
  305. try {
  306. zipOutputStream.close();
  307. } catch (IOException e) {
  308. e.printStackTrace();
  309. }
  310. }
  311. return true;
  312. }
  313. private static void zipFile(ZipOutputStream zipOutputStream, String sourcePath) throws IOException {
  314. File files = new File(sourcePath);
  315. File[] fileList = files.listFiles();
  316. String entryPath = &quot;&quot;;
  317. BufferedInputStream input;
  318. for (File file : fileList) {
  319. if (file.isDirectory()) {
  320. zipFile(zipOutputStream, file.getPath());
  321. } else {
  322. byte data[] = new byte[BUFFER_SIZE];
  323. FileInputStream fileInputStream = new FileInputStream(file.getPath());
  324. input = new BufferedInputStream(fileInputStream, BUFFER_SIZE);
  325. entryPath = file.getAbsolutePath().replace(parentPath, &quot;&quot;);
  326. ZipEntry entry = new ZipEntry(entryPath);
  327. zipOutputStream.putNextEntry(entry);
  328. int count;
  329. while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
  330. zipOutputStream.write(data, 0, count);
  331. }
  332. input.close();
  333. }
  334. }
  335. }
  336. public static Boolean unzip(String sourceFile, String destinationFolder) {
  337. ZipInputStream zis = null;
  338. try {
  339. zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
  340. ZipEntry ze;
  341. int count;
  342. byte[] buffer = new byte[BUFFER_SIZE];
  343. while ((ze = zis.getNextEntry()) != null) {
  344. String fileName = ze.getName();
  345. fileName = fileName.substring(fileName.indexOf(&quot;/&quot;) + 1);
  346. File file = new File(destinationFolder, fileName);
  347. File dir = ze.isDirectory() ? file : file.getParentFile();
  348. if (!dir.isDirectory() &amp;&amp; !dir.mkdirs())
  349. throw new FileNotFoundException(&quot;Invalid path: &quot; + dir.getAbsolutePath());
  350. if (ze.isDirectory()) continue;
  351. FileOutputStream fout = new FileOutputStream(file);
  352. try {
  353. while ((count = zis.read(buffer)) != -1)
  354. fout.write(buffer, 0, count);
  355. } finally {
  356. fout.close();
  357. }
  358. }
  359. } catch (IOException ioe) {
  360. Log.d(TAG, ioe.getMessage());
  361. return false;
  362. } finally {
  363. if (zis != null)
  364. try {
  365. zis.close();
  366. } catch (IOException e) {
  367. }
  368. }
  369. return true;
  370. }
  371. }

<!-- end snippet -->

答案1

得分: 0

以下是翻译好的内容:

这篇帖子已经过时,但是我对于使用单词列表无法生成密码的问题有解决方案。

显然,首先读取文件(可以来自存储或资源),并测试是否有效。如果有效,然后创建一个随机数选择器,并粘贴以下代码:

  1. public static int getRandomNumber(int min, int max) {
  2. return new Random().nextInt(max - min + 1) + min;
  3. }

要从单词列表中获取一个随机单词,使用:

  1. String[] lines = content.split(System.lineSeparator());
  2. int random = getRandomNumber(0, lines.length);
  3. String word = lines[random];

要生成新密码,建议使用<code>while</code>循环,直到达到最小长度(currentPassword 是一个字符串,我从我的项目中复制了代码(在我的 GitHub 页面上查看)):

  1. private void generateNewPassword() {
  2. currentPassword = "";
  3. while (currentPassword.length() <= minLength)
  4. currentPassword += lines[Utility.getRandomNumber(0, lines.length - 1)] + charsBetweenWords;
  5. if (replacesChars) {
  6. for (int i = 0; i < listFrom.size(); i++) {
  7. if (replacesCases) {
  8. String lowercase = listFrom.get(i).toLowerCase();
  9. String uppercase = listFrom.get(i).toUpperCase();
  10. currentPassword = currentPassword.replaceAll(lowercase, listTo.get(i));
  11. currentPassword = currentPassword.replaceAll(uppercase, listTo.get(i));
  12. } else {
  13. if (listTo.get(i).equals("$"))
  14. currentPassword = currentPassword.replaceAll(listFrom.get(i), "\\$");
  15. else if (listFrom.get(i).equals("$"))
  16. currentPassword = currentPassword.replaceAll("\\$", listTo.get(i));
  17. else if (listTo.get(i).equals("\\"))
  18. currentPassword = currentPassword.replaceAll(listFrom.get(i), "\\");
  19. else if (listFrom.get(i).equals("\\"))
  20. currentPassword = currentPassword.replaceAll("\\\\", listTo.get(i));
  21. else
  22. currentPassword = currentPassword.replaceAll(listFrom.get(i), listTo.get(i));
  23. }
  24. }
  25. }
  26. currentPassword = currentPassword.substring(0, currentPassword.length() - charsBetweenWords.length());
  27. passwordOutput.setText(currentPassword);
  28. }
英文:

This post is old, but I have the solution on who cannot progress with making passwords using a wordlist.

Obviously, first, read the file (can be from Storage or Assets) and test if that works. If this works, then create a random number picker and paste this following code:

  1. public static int getRandomNumber(int min, int max) {
  2. return new Random().nextInt(max - min + 1) + min;
  3. }

To get a random word out of the Wordlist, use

  1. String[] lines = content.split(System.lineSeparator());
  2. int random = getRandomNumber(0, lines.length);
  3. String word = lines[random];

And to generate a new password, it is recommended to use <code>while</code> to loop, until it hits the minimal length (currentPassword is a String and I copied the code from my project (see on my GitHub page))

  1. private void generateNewPassword() {
  2. currentPassword = &quot;&quot;;
  3. while (currentPassword.length() &lt;= minLength)
  4. currentPassword += lines[Utility.getRandomNumber(0, lines.length - 1)] + charsBetweenWords;
  5. if (replacesChars) {
  6. for (int i = 0; i &lt; listFrom.size(); i++) {
  7. if (replacesCases) {
  8. String lowercase = listFrom.get(i).toLowerCase();
  9. String uppercase = listFrom.get(i).toUpperCase();
  10. currentPassword = currentPassword.replaceAll(lowercase, listTo.get(i));
  11. currentPassword = currentPassword.replaceAll(uppercase, listTo.get(i));
  12. } else {
  13. if (listTo.get(i).equals(&quot;$&quot;))
  14. currentPassword = currentPassword.replaceAll(listFrom.get(i), &quot;\\$&quot;);
  15. else if (listFrom.get(i).equals(&quot;$&quot;))
  16. currentPassword = currentPassword.replaceAll(&quot;\\$&quot;, listTo.get(i));
  17. else if (listTo.get(i).equals(&quot;\\&quot;))
  18. currentPassword = currentPassword.replaceAll(listFrom.get(i), &quot;\\&quot;);
  19. else if (listFrom.get(i).equals(&quot;\\&quot;))
  20. currentPassword = currentPassword.replaceAll(&quot;\\\\&quot;, listTo.get(i));
  21. else
  22. currentPassword = currentPassword.replaceAll(listFrom.get(i), listTo.get(i));
  23. }
  24. }
  25. }
  26. currentPassword = currentPassword.substring(0, currentPassword.length() - charsBetweenWords.length());
  27. passwordOutput.setText(currentPassword);
  28. }

huangapple
  • 本文由 发表于 2020年3月15日 17:23:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/60691406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定